【问题标题】:(Python) How to take a variable from a message on discord using discord.py?(Python)如何使用 discord.py 从不和谐的消息中获取变量?
【发布时间】:2020-09-25 19:33:23
【问题描述】:

我正在编写一个简单的不和谐机器人来娱乐,我希望它在某个短语之后从消息中获取(例如)一个数字,并在以后使用它 例如,某个用户键入“$test 6”,我希望我的机器人获取该数字 (6),再举个例子,将其发送到同一频道。

我在创建此问题以拆分 message.content 后提出 它会起作用吗? (不算用户可以写数字以外的东西)

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)

【问题讨论】:

    标签: python discord.py


    【解决方案1】:

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

    @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}`")
    

    参考资料:

    【讨论】:

      猜你喜欢
      • 2020-12-12
      • 2021-08-24
      • 2020-12-13
      • 2021-07-31
      • 2019-04-14
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      • 2017-09-18
      相关资源
      最近更新 更多