Discord.py机器人没有上线,但仍然有效



我的discord机器人有问题,每当我使用apraw运行下面的代码来获取子reddit上最近提交的标题时,机器人就不再在线出现,但仍然以CMD:返回标题

  1. Bot在我执行此操作时未联机,但仍要求提供子reddit名称&在CMD中打印子reddit的新帖子的标题:
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就是问题所在。但是,为了让我的机器人在线,同时还能在给定的reddit子网站上检索新提交的标题,我需要改变什么样的检查?代码没有返回任何错误:/

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

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

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

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