Discord bot not running code or responding

Question:

this code is meant to run whatever code is inputted with a command into a computer i have no errors and the test message works but it doesn’t run the code in the computer when input with the command and it doesn’t respond with the message "Code executed successfully." or "An error occurred while executing the code."

i try to run the echo command

import discord
import asyncio

intents = discord.Intents.default()
intents.members = True

client = discord.Client(intents=intents)


@client.event
async def on_ready():
    print('Bot is online and connected to Discord!')
    await client.change_presence(activity=discord.Game(name='with code'))
    # Send test message
    test_channel = client.get_channel(channel_id_here)
    await test_channel.send('Bot is working and ready to execute code.')

@client.event
async def on_message(message):
    if message.content.startswith('!runcode'):
        # Get the code to run
        code = message.content[8:]
        try:
            exec(code)
            await message.channel.send('Code executed successfully.')
        except:
            await message.channel.send('An error occurred while executing the code.')

client.run('My_Bot_Token_Here')

i tried using anything to try to debug it chatgpt, special debuggers, etc. but nothing shows me the -problem and when i try to run this: !runcode msg * "Your message here" nothing shows up

Asked By: peakyru

||

Answers:

Try this code below, because simply, the exec() function runs the code inputted in the command, but it doesn’t return anything. That’ s why you don’t see any output. And the command you are trying to run (echo) is not even a python command it is a shell command..

import subprocess

@client.event
async def on_message(message):
    if message.content.startswith('!runcode'):
        # Get the code to run
        code = message.content[8:]
        try:
            output = subprocess.run(code, shell=True, capture_output=True)
            output_str = output.stdout.decode()
            await message.channel.send(f'Code executed successfully.nOutput: {output_str}')
        except Exception as e:
            await message.channel.send(f'An error occurred while executing the code.nError: {e}')
Answered By: Nova
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.