Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- from dotenv import dotenv_values
- config = dotenv_values('config.env')
- import asyncio
- from threading import Thread
- import time
- import discord
- TOKEN = config['DISCORD_TOKEN']
- ROLL_CHANNEL = 'myrolls' # Instead of this, use a channelID. Even better, register channelIDs given by users
- bot = discord.Client()
- '''Set up an asyncio event loop on a different thread, returning the loop's handle so other threads can message it'''
- def launch_bot():
- loop = asyncio.new_event_loop()
- loop.create_task(bot.start(TOKEN))
- Thread(target=loop.run_forever).start()
- return loop
- '''This is what the bot does once discordpy connects to it'''
- @bot.event
- async def on_ready():
- for channel in bot.get_all_channels():
- if channel.name == ROLL_CHANNEL:
- await channel.send("Good morning!")
- '''Displays a dice roll using the bot'''
- async def dice_roll(message):
- for channel in bot.get_all_channels():
- if channel.name == ROLL_CHANNEL:
- await channel.send(message)
- '''And here's how you get the GUI to safely send the dice_roll to the bot's async thread'''
- def send_roll(loop_handle, message):
- asyncio.run_coroutine_threadsafe(dice_roll(message), loop_handle)
- print(message)
- if __name__ == '__main__':
- loop = launch_bot()
- while True:
- time.sleep(5)
- send_roll(loop, 'Hello!')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement