DEV Community

Juan Carlos
Juan Carlos

Posted on

Discord Bot on 1 Tweet


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

Enter fullscreen mode Exit fullscreen mode
  • 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:
  try:
    echo "Starting Discord Bot"
    waitFor bot.startSession() # Run Bot
  finally:
    echo "Stopping Discord Bot"
    waitFor bot.disconnect()   # Stop Bot

Enter fullscreen mode Exit fullscreen mode

Discordnim

  • The objects and API are on the discordnim lib.

GitHub logo Krognol / discordnim

Discord library for nim

Discordnim

A Discord library for Nim.

Websockets from niv/websocket.nim

Installing

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

Usage

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()

    setControlCHook(endSession)
    d.compress = true
    let removeProc = d.addHandler(EventType
…
Enter fullscreen mode Exit fullscreen mode

Social

Alt Text

Top comments (0)