Search code examples
pythonpython-3.xdiscorddiscord.pypython-os

How to run discordpy terminal in bot


i was looking to make a command for my bot that would allow me to run commands directly through the bot suchas:

input: /run await ctx.send("hi stackoverflow")

bot: hi stackoverflow

I have been researching how to make such a command in discordpy, but the closest i got was using exec, but it just threw up discord.ext.commands.errors.CommandInvokeError: Command raised an exception: SyntaxError: 'await' outside function (<string>, line 1)

I hate to ask without proper code samples but any help is appreciated <3


Solution

  • If you are looking for a command line interface, I would suggest something like this:

    import threading, time
    
    
    def waitfor():
        cmd = input('command: ')
        print(cmd)
        ## do command processing here eg. eval(cmd)
    
    def runthread():
        t = threading.Thread(target=waitfor)
        t.start()
        return t
    
    async def commandInterface():
        t = runthread()
        while 1:
            if not t.is_alive():
                t = runthread()
            time.sleep(1)
            ## loop stuff
    
    client.loop.create_task(commandInterface)
    client.run(TOKEN)
    

    This uses the threading module to wait for an input and the run the command, without blocking the rest of the program. Obviously it would need to be adapted to fit your needs but this could be a good start.