【问题标题】:Discord.py Bot is not online, but still worksDiscord.py Bot 不在线,但仍然有效
【发布时间】:2021-06-13 04:23:27
【问题描述】:

我的 discord bot 有问题,每当我使用 apraw 运行下面的代码以获取 subreddit 上最近提交的标题时,bot 不再在线显示,但仍返回 CMD 中的标题:

  1. 当我执行此操作时,Bot 不在线,但仍然要求 subreddit 名称并在 CMD 中打印 subreddit 的新帖子的标题:
import asyncio
import apraw
from discord.ext import commands

bot = commands.Bot(command_prefix = '?')

@bot.event
async def on_ready():
    print('Bot is ready')
    await bot.change_presence(status=discord.Status.online, activity=discord.Game('?'))

@bot.command()
async def online (ctx):
    await ctx.send('Bot is online !')

reddit = apraw.Reddit(client_id = "CLIENT_ID",
                      client_secret = "CLIENT_SECRET",
                      password = "PASSWORD",
                      user_agent = "pythonpraw",
                      username = "LittleBigOwl")

@bot.event
async def scan_posts():
    xsub = str(input('Enter subreddit name : '))
    subreddit = await reddit.subreddit(xsub)
    async for submission in subreddit.new.stream():
        print(submission.title)

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(scan_posts())


bot.run('TOKEN')
  1. 但当我执行此操作时在线但显然不要求子名称...:
import asyncio
import apraw
from discord.ext import commands

bot = commands.Bot(command_prefix = '?')

@bot.event
async def on_ready():
    print('Bot is ready')
    await bot.change_presence(status=discord.Status.online, activity=discord.Game('?'))

@bot.command()
async def online (ctx):
    await ctx.send('Bot is online !')


bot.run('TOKEN')

所以 reddit 是这里的问题。但是,为了让我的机器人在线出现,同时仍然能够在给定的 subreddit 上检索新提交的标题,我应该改变什么?代码没有返回任何错误:/

【问题讨论】:

  • 你究竟是如何触发scan_posts的,因为那不是不和谐事件
  • @Ceres idk,scan_posts 自行触发,当我尝试删除 @bot.event 时,我仍然遇到同样的问题
  • 这不应该发生,当你启动机器人时它会打印Enter subreddit name : 吗? @bot.event 装饰器用于修改脚本在发生不和谐事件(例如on_messageon_ready)时所做的事情。你到底想让scan_posts做什么?你为什么用@bot.events装饰它。

标签: discord.py offline reddit praw


【解决方案1】:

您放在async def scan_posts(): 上方的@bot.event 应更改为@bot.command()。它会自行触发,因为您的代码中有这个:

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(scan_posts())

这就是导致scan_posts 自动运行的原因。您应该删除它,因为您希望 scan_posts 成为机器人命令,而不是自动发生的事情。由于此代码,该机器人也没有上线。它的作用是检查此文件是否已运行,然后运行scan_posts。其余代码不会被触发。 此外,您不应更改 on_ready 中的存在,因为 Discord 很有可能在 on_ready 事件期间完全断开您的连接,您无法阻止它。相反,您可以在commands.Bot 中使用activitystatus kwargs,例如:

bot = commands.Bot(command_prefix = '?', status=discord.Status.online, activity=discord.Game('?'))

【讨论】:

    猜你喜欢
    • 2021-08-31
    • 2022-01-11
    • 2012-07-13
    • 1970-01-01
    • 2015-06-21
    • 1970-01-01
    • 2018-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多