python - 使用 discord.py 将 wait_for 中的消息转换为频道
问题描述
我有一种wait_for
创建反应角色的命令方法:
msg = await self.bot.wait_for('message', check=checkChannel, timeout=60)
它利用该checkChannel
功能来验证消息是“取消”(取消创建)还是公会中的频道。我的原始代码:
def checkChannel(msg):
if ctx.message.author == msg.author and ctx.channel == msg.channel:
if (msg.content == "Cancel"):
return True
nonlocal embedChannel
message = msg.content
if message.startswith("<#"):
message = message[2:len(message) - 1]
for channel in self.bot.get_guild(ctx.guild.id).channels:
if str(channel.id) == message:
embedChannel = channel
return True
return False
else:
return False
由于这特别混乱(并且不考虑发送频道名称),我尝试寻找一种更有效的方法并得到了这个答案:
channel = await commands.TextChannelConverter().convert(ctx, args)
但是,由于这使用await
并需要async
语法,因此我无法在 check 函数的上下文中使用它,并且会得到:
RuntimeWarning: coroutine '<directory>.checkChannel' was never awaited
我将如何克服这一点?
解决方案
有人告诉我,克服它的最有效方法是创建一个循环(在外部函数内部)并channel = await commands.TextChannelConverter().convert(ctx, args)
在那里调用,以便实际调用它。
因此,在这种情况下,它将是:
def checkChannel(msg):
return ctx.message.author == msg.author and ctx.channel == msg.channel
channel_checker = True
while channel_checker == True:
try:
msg = await self.bot.wait_for('message', check=checkChannel, timeout=60)
except asyncio.TimeoutError:
await ctx.send(f"You took too long to respond")
return
if msg == "cancel":
await ctx.send("Cancelling...")
return
try:
embedChannel = await commands.TextChannelConverter().convert(ctx, msg.content)
channel_checker = False
except:
await ctx.send(f"Retry typing in the channel")
#Continue creating...
推荐阅读
- pdf - 从 PDF 文件复制时印地语内容失真
- amazon-web-services - ECS 集群中没有实例
- sql - 在同一查询中使用查询结果字段作为数据库名称
- tensorflow - Tensorflow dense_image_warp 无法转换类型的对象
张量 - django - 将数据添加到数据库后更新 Django 表单
- auth0 - Auth0 PasswordLess - 在锁定 11 中为用户提供电子邮件和短信验证选项
- .htaccess - Redirect all pages ( from a server to another's homepage) except one
- active-directory - Active Directory 中“人员”和“用户”OU 之间的区别
- node.js - How to use Ziggy package in Typescript
- django - Python django 添加多个数据库