为了账号安全,请及时绑定邮箱和手机立即绑定

“上下文”对象没有属性“reddit”Discord.PY

“上下文”对象没有属性“reddit”Discord.PY

哔哔one 2022-12-20 15:27:57
我正在尝试向.reddit我的机器人添加命令。这是我的代码: @client.command(name="random", aliases=["reddit"]) async def _random(ctx, subreddit: str = ""):    reddit = None    if reddit_app_id and reddit_app_secret:        reddit = praw.Reddit(client_id=reddit_app_id,client_secret=reddit_app_secret,user_agent="MASTERBOT:%s1.0" % reddit_app_id)    if reddit:        submissions = reddit.subreddit(subreddit).hot()        submission = next(x for x in submissions if not x.stickied)        await ctx.send(submissions.url)我已经导入了所有内容,一切似乎都很好,直到出现此错误:discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Command' object has no attribute 'randint'据我了解,该程序不知道什么是 randint。我检查了我是否打错了字,但没有。一切似乎都很好。我在同一命令上遇到了错误,但我设法修复了它。但这一个抓住了我,我需要你的帮助。这些是新错误:AttributeError: 'coroutine' object has no attribute 'url'.RuntimeWarning: Enable tracemalloc to get the object allocation traceback
查看完整描述

1 回答

?
噜噜哒

TA贡献1784条经验 获得超7个赞

你有 Cog(类)中的命令吗?


如果不这样做,那么您应该删除self,因为它会假定那是context对象的名称。


@client.command(name="random", aliases=["reddit"])

async def _random( ctx, subreddit: str = ""):

    reddit = None

    if reddit_app_id and reddit_app_secret:

        reddit = praw.Reddit(client_id=reddit_app_id,client_secret=reddit_app_secret,user_agent="MASTERBOT:%s1.0" % reddit_app_id)

    if reddit:

        chosen_subreddit = reddit_enabled_meme_subreddits[0]

        if subreddit:

            if subreddit in reddit_enabled_meme_subreddits:

                chosen_subreddit = subreddit

        submissions = reddit.subreddit(chosen_subreddit).hot()

        post_to_pick = random.randint(1, 10)

        for i in range(0, post_to_pick):

            submission = next(x for x in submissions if not x.stickied)

        await ctx.send(submission.url)

    else:

        await ctx.send("This is not working")

问题出在命令的名称上random,因为这会污染random模块的命名空间。您可以通过重命名命令来绕过它。


与代码顶部的冲突async def random(....。import random您可以name=在装饰器中使用关键字参数设置命令的名称。这就是人们将输入不和谐的名字。


尝试使用您获得随机提交的方法(减去多余的代码,只是相同的逻辑),它对我有用:


reddit = praw.Reddit(client_id="...", client_secret="...", user_agent="...")


@bot.command(name="reddit")

async def _reddit(ctx, subreddit: str = ""):

    submissions = reddit.subreddit(subreddit).hot()

    submission = next(x for x in submissions if not x.stickied)

    await ctx.send(submission.url)

我唯一能想到的就是确保您拥有最新版本的praw,并且如果命令中还有其他您可能遗漏的问题,那么这可能会影响它,尽管那只是猜测。


我会说尝试从头开始发出命令。从简单的东西开始,逐行添加,直到出现问题。然后你就会知道是什么原因造成的RuntimeWarning等等。


很抱歉对此没有明确的答案。


查看完整回答
反对 回复 2022-12-20
  • 1 回答
  • 0 关注
  • 86 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信