Untitled

mail@pastecode.io avatar
unknown
python
a year ago
2.0 kB
2
Indexable
Never
import discord
import pickle
import json

commands = {}

async def send_message(message, user_message):
    try:
        print(commands)
        response = handle_response(user_message)
        if response != None:
            await message.channel.send(response)
    except Exception as e:
        print(e)

def update_backup():
    print("UB")
    with open('commands_data.pkl', 'wb') as f:
        pickle.dump(commands, f)

def load_backup():
    print("LB")
    with open('commands_data.pkl', 'rb') as f:
        commands = pickle.load(f)
    print(str(commands))

def handle_cmd(key, value) -> str:
    if commands.get(key) != None:
        return 'This command already exists with this value : ' + commands[key]
    
    commands[key] = value
    update_backup()
    return 'New command "!'+ key + '" added : ' + value

def handle_response(msg) -> str:
    load_backup()
    print(commands)
    msgs = msg.split(' ')

    if commands.get(msgs[0]) != None:
        return commands[msgs[0]]

    if msgs[0] == 'add':
        return handle_cmd(msgs[1], msgs[2])

    if msgs[0] == 'mercredi':
        return 'https://cdn.discordapp.com/attachments/1155501614073921536/1155505206625312851/unknown.png'
    
    if msgs[0] == 'help':
        return 'help'    

    
def get_token() -> str:
    with open('token.json', 'r') as f :
        data = json.load(f)
    return data["BOT_TOKEN"]

def run_discord_bot():
    intents = discord.Intents.default()
    intents.message_content = True
    client = discord.Client(intents = intents)
    load_backup()

    @client.event
    async def on_ready():
        print(f'{client.user} is running')

    @client.event
    async def on_message(message):
        if message.author == client.user:
            return
        
        user = str(message.author)
        msg = str(message.content)


        if msg[0] != '!':
            return
        else:
            msg = msg[1:]
            await send_message(message, msg)
    
    client.run(get_token())