首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >(Python)如何使用discord.py从消息中提取变量?

(Python)如何使用discord.py从消息中提取变量?
EN

Stack Overflow用户
提问于 2020-06-06 16:45:28
回答 1查看 451关注 0票数 1

为了好玩,我正在编写一个简单的不和谐机器人,我希望它在某个短语之后从消息中获取一个数字,然后使用它--例如,一个特定的用户类型"$test 6“--我希望我的机器人接受这个数字(6),并在另一个例子中将它发送到同一个频道。

我是在创建了这个问题来拆分message.content之后出现的,它能工作吗?(不包括用户可以写数字以外的东西)

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-06 17:22:58

这可以通过命令参数来完成:

代码语言:javascript
复制
@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}")

还有一个使用一些不和谐对象的例子:

代码语言:javascript
复制
@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}`")

参考资料:

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62234901

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档