Advertisement
Kitsunay

Async Discordpy

Jul 8th, 2022 (edited)
1,257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.37 KB | None | 0 0
  1. import os
  2. from dotenv import dotenv_values
  3. config = dotenv_values('config.env')
  4.  
  5. import asyncio
  6. from threading import Thread
  7. import time
  8.  
  9. import discord
  10.  
  11. TOKEN = config['DISCORD_TOKEN']
  12. ROLL_CHANNEL = 'myrolls'  # Instead of this, use a channelID. Even better, register channelIDs given by users
  13.  
  14. bot = discord.Client()
  15.  
  16. '''Set up an asyncio event loop on a different thread, returning the loop's handle so other threads can message it'''
  17. def launch_bot():
  18.     loop = asyncio.new_event_loop()
  19.     loop.create_task(bot.start(TOKEN))
  20.     Thread(target=loop.run_forever).start()
  21.     return loop
  22.  
  23. '''This is what the bot does once discordpy connects to it'''
  24. @bot.event
  25. async def on_ready():
  26.     for channel in bot.get_all_channels():
  27.         if channel.name == ROLL_CHANNEL:
  28.             await channel.send("Good morning!")
  29.  
  30. '''Displays a dice roll using the bot'''
  31. async def dice_roll(message):
  32.     for channel in bot.get_all_channels():
  33.         if channel.name == ROLL_CHANNEL:
  34.             await channel.send(message)
  35.  
  36. '''And here's how you get the GUI to safely send the dice_roll to the bot's async thread'''
  37. def send_roll(loop_handle, message):
  38.     asyncio.run_coroutine_threadsafe(dice_roll(message), loop_handle)
  39.     print(message)
  40.  
  41. if __name__ == '__main__':
  42.     loop = launch_bot()
  43.     while True:
  44.         time.sleep(5)
  45.         send_roll(loop, 'Hello!')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement