首页 > 解决方案 > (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)

标签: pythondiscord.py

解决方案


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

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

参考:


推荐阅读