嗨我试图让我的不和谐机器人做我正在输入我的不和谐客户端,我想使用exec()+这只是为了测试和实验所以它无关紧要,如果它可能是不安全的。
我的部分代码:
import discord
client = discord.Client()
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('2B: '):
exec(message.content[4:]) # <--- here is the exec()
.
.
.
但是当我输入时,这是错误,
2B: await client.send_message(message.channel, 'please stay quiet -.-')
错误:
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Shiyon\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\client.py", line 307, in _run_event
yield from getattr(self, event)(*args, **kwargs)
File "C:\Users\Shiyon\Desktop\dm_1.py", line 12, in on_message
exec(message.content[4:])
File "<string>", line 1
await client.send_message(message.channel, 'please stay quiet -.-')
^
SyntaxError: invalid syntax
答案 0 :(得分:4)
我相信这可能是你的问题:
请注意,即使在传递给exec()函数的代码的上下文中,return和yield语句也不能在函数定义之外使用
来自https://docs.python.org/3/library/functions.html
这应该更好:
await eval(input)
如果您希望能够使用非协同程序,则可以在等待eval返回之前进行检查。
以下是来自Rapptz's bot的代码段,它似乎可以执行您想要的内容:
@commands.command(pass_context=True, hidden=True)
@checks.is_owner()
async def debug(self, ctx, *, code : str):
"""Evaluates code."""
code = code.strip('` ')
python = '```py\n{}\n```'
result = None
env = {
'bot': self.bot,
'ctx': ctx,
'message': ctx.message,
'server': ctx.message.server,
'channel': ctx.message.channel,
'author': ctx.message.author
}
env.update(globals())
try:
result = eval(code, env)
if inspect.isawaitable(result):
result = await result
except Exception as e:
await self.bot.say(python.format(type(e).__name__ + ': ' + str(e)))
return
await self.bot.say(python.format(result))
解释编辑:
await
关键字仅适用于上下文,因为它在循环中暂停执行时会有一些魔力。
exec
函数始终返回None
并丢失它执行的任何语句的返回值。相比之下,eval
函数返回其语句的返回值。
client.send_message(...)
返回一个等待的对象,需要在上下文中等待。通过在await
返回时使用eval
,我们可以轻松地执行此操作,并通过检查它是否等待,我们也可以执行非协同程序。