Discord Bot on 1 Tweet

juancarlospaco profile image Juan Carlos ・1 min read

import asyncdispatch, discordnim

let bot = newShard("Bot KEY")  # KEY is a valid Discord "Token" Key

proc f(b: Shard, m: MessageCreate) =  # Async Event Handler 
  discard b.channelMessageSend(m.channel_id, m.content)

discard bot.addHandler(EventType.message_create, f) # Hook Handler

waitFor bot.startSession()  # Run Bot

  • Ideally you need to add asyncCheck instead of discard, and a disconnect() at exit for the bot, but basically is a working async chat bot!.
import asyncdispatch, os, discordnim

let bot = newShard("Bot " & getEnv("DISCORD_TOKEN"))  # DISCORD_TOKEN is a valid Discord "Token" Key

proc callback(bot: Shard, mesage: MessageCreate) =  
  ## Async Event Handler 
  if mesage.author.id != bot.cache.me.id: # Bot wont reply itself
    echo mesage.content
    case mesage.content # case switch on message content
    of "!help":         # message content is "!help"
      asyncCheck bot.channelMessageSend(mesage.channel_id, "Some help")
    of "!ping":         # message content is "!ping"
      asyncCheck bot.channelMessageSend(mesage.channel_id, "pong")
    else:               # message content is something else                 
      asyncCheck b.channelMessageSend(mesage.channel_id, mesage.content)

discard bot.addHandler(EventType.message_create, callback) # Hook Handler

when isMainModule:
    echo "Starting Discord Bot"
    waitFor bot.startSession() # Run Bot
    echo "Stopping Discord Bot"
    waitFor bot.disconnect()   # Stop Bot


  • The objects and API are on the discordnim lib.

GitHub logo Krognol / discordnim

Discord library for nim


A Discord library for Nim.

Websockets from niv/websocket.nim


This assumes that you have your Nim environment (including Nimble) already set up, and that your Nim version is 1.0.4 or greater You can check your version with nim --version

nim -v
Nim Compiler Version 1.1.1 [Linux: amd64]
Compiled at 2020-01-08
Copyright (c) 2006-2019 by Andreas Rumpf
active boot switches: -d:release

nimble install discordnim


There are some examples in the examples folder.

Initialising a Shard:

when isMainModule
    import asyncdispatch, discordnim, ospaths
    proc messageCreate(s: Shard, m: MessageCreate) =
        if s.cache.me.id == m.author.id: return
        if m.content == "ping":
            asyncCheck s.channelMessageSend(m.channel_id, "pong")

    let d = newShard("Bot " & getEnv("token")) // get token in environment variables

    proc endSession() {.noconv.} =
        waitFor d.disconnect()

    d.compress = true
    let removeProc = d.addHandler(EventType


Alt Text

Posted on by:

juancarlospaco profile

Juan Carlos


.10x frAgile FullStuck Midend Devlooper, Python, Nim, Arch, OpenSource, EN|ES, Argentina, UTC-3, Atheist, WFH Nim Team Leader


markdown guide