我正在制作一个discord机器人,它发送新上传的书籍,我收到了这个错误

2024-10-01 07:26:39 发布

您现在位置:Python中文网/ 问答频道 /正文

问题是,当我使用!firsttime命令时,我得到的错误是

Ignoring exception in command firsttime:

Traceback (most recent call last):
  File "goodreads.py", line 27, in firsttime_command
    for link in links.reverse():
TypeError: 'NoneType' object is not iterable

上述异常是以下异常的直接原因

这是密码

import re
import json
import aiohttp
from datetime import datetime

import discord
from discord.ext import commands, tasks

JSON_PATH = "json file path"
REGEX = "<a class=readable bookTitle href=(.*)[?].*>"
URL = "https://www.goodreads.com/genres/new_releases/fantasy"
CHANNEL_ID = 834867425677803580

class Goodreads(commands.Cog):
  def __init__(self, bot):
    self.bot = bot

  @commands.Cog.listener()
  async def on_ready(self):
    self.check_website.start()

  @commands.command(name="firsttime")
  async def firsttime_command(self, ctx):
    links = await self.make_request()
    data = {}
    now = str(datetime.utcnow())
    for link in links.reverse():
      data[link] = now
    with open(JSON_PATH, "w") as f:
      json.dump(data, f, indent=2)

  @tasks.loop(minutes=1)
  async def check_website(self):
    links = await self.make_request()

with open(JSON_PATH, "r") as f:
  data = json.load(f)

for link in links:
  if link not in data.keys():
    await self.bot.get_channel(CHANNEL_ID).send(f"A new fantasy book released.\n{link}")
    data[link] = str(datetime.utcnow())
    with open(JSON_PATH, "w") as f:
      json.dump(data, f, indent=2)

  async def make_request(self):
    async with aiohttp.ClientSession() as ses:
      async with ses.get(URL) as res:
        text = await res.text()
        text = text.replace("\\\"", "")
        return re.findall(REGEX, text)

bot = commands.Bot(command_prefix="!")
bot.add_cog(Goodreads(bot))

@bot.event
async def on_connect():
  print("Connected")

@bot.event
async def on_ready():
  print("Ready")

bot.run("tokens")

Tags: inimportselfjsondataasyncdefas
1条回答
网友
1楼 · 发布于 2024-10-01 07:26:39

在深入研究代码并使用print()检查变量中的值之后,我发现所有的问题都已解决

.reverse() 

它在in-place中起作用-因此它改变了原始列表中的顺序并返回None

你必须这样做

 links.reverse()

 for link in links:
     #... code ...

或者你应该使用reversed()

 for link in reversed(links):
     #... code ...

或者,您可以使用slice进行此操作

 for link in links[::-1]:
     #... code ...

顺便说一句:list.sort()sorted(list)也是如此

相关问题 更多 >