You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Praw开发Discord随机马图推送机器人运行报错求助

问题根因
  • 你用@client.command()装饰器定义的horse函数,强制要求传入Discord上下文参数ctx,但你在on_message事件中调用await horse()时没有传入任何参数,直接触发了参数缺失报错。
  • 你初始化Bot时设置了command_prefix=None,等于禁用了所有前缀触发的指令,就算补了ctx参数,原本的装饰器注册逻辑也没法正常生效。
  • 自定义on_message事件后如果没有主动调用await client.process_commands(message),所有@client.command()注册的指令都会被事件拦截,不会自动触发。
修复方案

这里直接适配你想要的「输入关键词horse就发图」的逻辑,不用依赖Discord的命令框架,调整后代码如下:

from typing import Any, Iterator

TOKEN = '你的实际Bot Token'

from discord.ext import commands
import random
import praw


client = commands.Bot(description="horse", command_prefix=None)
reddit = praw.Reddit(client_id='你的Reddit应用client_id',
                     client_secret='你的Reddit应用client_secret',
                     user_agent='horse bot')

# 把获取马图的逻辑拆成独立函数,不需要ctx参数
async def get_horse_img():
    horses_submissions = reddit.subreddit('horses').hot(limit=100)
    horses_submissions = [x for x in horses_submissions if not x.stickied]
    submission = random.choice(horses_submissions)
    return submission.url

@client.event
async def on_ready():
    print('the ranch! the ranch! {0.user} has joined the ranch!'.format(client))

@client.event
async def on_message(message):
    username = str(message.author).split('#')[0]
    user_message = str(message.content)
    channel = str(message.channel.name)
    print(f'{username}: {user_message} ({channel})')

    if message.author == client.user:
        return
    if message.channel.name == 'the-ranch':
        if user_message.lower() == 'hello':
            await message.channel.send(f'greetings {username}! give me oats')
            return
        elif user_message.lower() == 'bye':
            await message.channel.send(f'please bring oats when you return, {username}..')
            return
        elif user_message.lower() == "!random":
            response = f' Here, have a random number, (as a treat): {random.randrange(1000000)}'
            await message.channel.send(response)
            return

    if user_message.lower() == '!anywhere':
        await message.channel.send('hey i am here too')

    # 触发马图逻辑
    if message.content.lower().startswith('horse'):
        horse_url = await get_horse_img()
        await message.channel.send(horse_url)


client.run(TOKEN)
额外注意事项
  • 确保你的Reddit应用的client_id、client_secret填写正确,否则会无法拉取子版块内容。
  • 确保机器人有对应频道的发消息权限,否则发图会被拦截。

内容的提问来源于stack exchange,提问作者moss icon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 19:57:02