Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Synchronized Discord bot in Python 3.
from discord import Client, CategoryChannel
import discord.utils
from time import sleep
import threading
import asyncio
import os
class Bot(Client):
guild = None
guild_id = os.getenv("DISCORD_GUILD_ID", None)
TOKEN = os.getenv("DISCORD_BOT_TOKEN", None)
def __init__(self):
super().__init__()
loop = asyncio.get_event_loop()
loop.create_task(self.start(self.TOKEN))
thread = threading.Thread(target=loop.run_forever)
thread.daemon = True
thread.start()
while not self.is_ready():
sleep(0.1)
def run_async(self, function):
self.loop.create_task(function)
def set_guild(self):
self.guild = self.get_guild(self.guild_id)
return bool(self.guild)
def normalize_channel_name(self, string):
return string.replace(" ","-").lower()
def normalize_category_name(self, string):
return string.replace(" ", "").lower()
def get_category(self, category_name):
return discord.utils.get(self.guild.categories, name=category_name)
def get_channel(self, channel_name, category):
return discord.utils.get(category.channels, name=channel_name)
def create_channel(self, channel_name, category_name):
category = self.get_category(category_name)
if not self.get_channel(channel_name, category):
self.run_async(self.guild.create_text_channel(channel_name, category=category))
def delete_channel(self, channel_name, category_name):
category = self.get_category(category_name)
channel = self.get_channel(channel_name, category)
if channel:
self.run_async(channel.delete())
def send_message(self, message, channel_name, category_name):
category = self.get_category(category_name)
channel = self.get_channel(channel_name, category)
self.run_async(channel.send(message))
bot = Bot()
bot.send_message("this is a synchronized message without the need of an async method", "channel", "category")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment