问题是当我使用 !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")
答案 0 :(得分:1)
在挖掘代码并使用 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)