python - (Python)如何使用 discord.py 从不和谐的消息中获取变量?
问题描述
我正在写一个简单的不和谐机器人来取乐,我希望它在某个短语之后从消息中获取(例如)一个数字,然后稍后使用它,例如某个用户键入“$test 6”,我希望我的机器人接受该数字( 6 ),另一个示例将其发送到同一频道。
我在创建此问题以拆分消息后提出。内容会起作用吗?(不算用户可以写除数字以外的东西)
import discord
client = discord.Client()
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith("$test"):
stringOne = str(message.content)
stringTwo = "$test "
split = stringOne.partition(stringTwo)[2]
await message.channel.send("number/s from your message: " + split)
解决方案
这可以通过命令参数来完成:
@bot.command()
async def test(ctx, number = None):
if not number:
await ctx.send("Please enter a number, for example: `$test 5`")
else:
await ctx.send(f"Here's the number you gave me: {number}")
还有一个使用一些不和谐对象的例子:
@bot.command()
async def kick(ctx, member: discord.Member = None, *, reason = "Default reason"):
if not member:
await ctx.send("Please provide a member for me to kick!")
else:
await member.kick(reason=reason)
await ctx.send(f"Successfully kicked {member} for `{reason}`")
参考:
- f-字符串- Python 3.6.0+
*
参数中的用法commands.Command()
- 为您的机器人创建/注册命令的装饰器。commands.Context
- 这将始终作为命令中的第一个参数传递。Context.send()
-Context
继承自abc.Messageable
,这意味着您可以向执行命令的通道发送消息。abc.Messageable
discord.Member
Member.kick()
推荐阅读
- dart - 颤振底片圆角半径
- android - 如何使 FragmentActivity 扩展 AppCompat 以使用工具栏?
- android - 程序类型已经存在 - Tipsi-Stripe
- javascript - 使用 JavaScript 将定时事件绑定到 DOM 对象
- spring - 如何解决spring bean不可用错误?
- cygwin - 为什么cygwin终端只在桌面上显示.lnk,没有文件夹?
- json - 如何在颤振/飞镖中比较 Json 数据方法
- python - Pyramid 中的这个结构是什么意思?
- php - 在 Woocommerce 中隐藏无运输方式消息
- python - 在 Python 3.0 中查找和替换列表元素?