【问题标题】:'Context' object has no attribute 'reddit' Discord.PY“上下文”对象没有属性“reddit”Discord.PY
【发布时间】:2020-09-22 16:24:44
【问题描述】:

我正在尝试向我的机器人添加 .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

【问题讨论】:

    标签: python discord.py


    【解决方案1】:

    你有 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= 关键字参数设置命令的名称。这是人们在 discord 中输入的名称。


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

    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等等。

    很抱歉没有明确的答案。

    【讨论】:

    猜你喜欢
    • 2019-06-19
    • 1970-01-01
    • 1970-01-01
    • 2020-12-17
    • 2021-07-27
    • 2021-01-05
    • 2021-03-06
    • 2019-08-13
    • 1970-01-01
    相关资源
    最近更新 更多