discord.py Объект ‘NoneType’ не может быть подписан

#python #discord #discord.py

#питон #Discord #discord.py

Вопрос:

Я получаю ошибки в if datetime.now() gt; datetime.strptime(str(expire['expiration']), "%Y-%m-%d %H:%M:%S"): том, что объект «Нетип» не доступен для подписки, ну, я искал в StackOverflow и не смог решить свою проблему, сначала я подумал, что это проблема с строкой, но у меня есть данные в моем MySQL.

 import discord, asyncio, os, json, pymysql.cursors from discord.ext import commands import databaseconnection from datetime import datetime, timedelta   # Opens/Read the Config file with open("configs/config.json") as f:  data = json.load(f)   con = databaseconnection.connection  bot = commands.Bot(command_prefix=data["prefix"]) bot.remove_command('help')   @bot.event async def on_message(message):  with con.cursor() as cursor:  cursor.execute("SELECT * FROM `info` WHERE `discord_id`=%s", (str(message.author.id)))  expire = cursor.fetchone()  if datetime.now() gt; datetime.strptime(str(expire['expiration']), "%Y-%m-%d %H:%M:%S"):  embed = discord.Embed(  color = discord.Color.dark_red(),  timestamp = datetime.utcnow()  )  embed.set_author(name="❗️ ERROR ❗️", icon_url="https://c.tenor.com/2gdcdzl-xaoAAAAM/error-computer.gif")  embed.add_field(name="__INFO:__", value=f"Your plan has been removed! Due to expiration.")  embed.set_footer(text="Evil Genios", icon_url="https://cdn.discordapp.com/icons/904638053396672532/643055721178f74ad6a0f1e46843410e.png?size=96")   await message.channel.send(embed=embed)  await asyncio.sleep(5)  with con.cursor() as icursor:  icursor.execute("DELETE FROM `info` WHERE `discord_id`=%s", (message.author.id))  r = icursor.fetchone()  con.commit()  embed1 = discord.Embed(  colour = discord.Color.dark_green(),  timestamp = datetime.utcnow()  )  embed1.set_author(name="❗️ SYSTEM ❗️", icon_url="http://www.happy32.in/images/checkmarksuccess.gif")  embed1.add_field(name="__INFO:__",value=f"`{message.author}`s has been removed!", inline=False)  embed1.set_footer(text="Evil Genios", icon_url="https://cdn.discordapp.com/icons/904638053396672532/643055721178f74ad6a0f1e46843410e.png?size=96")  await message.channel.send(embed=embed1)     # Loads the Cogs and shit @bot.event async def on_ready():  print('loaded!')  for filename in os.listdir("cogs"):  if filename.endswith('.py'):  bot.load_extension(f"cogs.{filename[:-3]}")    # Runs the bot bot.run("mfa.E-Sc02z7AZ70ZiVV0PPuJC05WxGlSe7QLtG4YuWa6VO__z2OuAiLFLazFjrUOrr11cow2M6DWT_filFY9T9Q", bot=False) #bot.run("ODgyNjEyODk0ODg0MzE5Mjgy.YS-Y2Q.ta-xQHrdu4rrD-bwKvAeEiGGnoQ", bot=False)import discord, asyncio, os, json, pymysql.cursors from discord.ext import commands import databaseconnection from datetime import datetime, timedelta   # Opens/Read the Config file with open("configs/config.json") as f:  data = json.load(f)   con = databaseconnection.connection  bot = commands.Bot(command_prefix=data["prefix"], self_bot=True) bot.remove_command('help')   @bot.event async def on_message(message):  with con.cursor() as cursor:  cursor.execute("SELECT * FROM `info` WHERE `discord_id`=%s", (str(message.author.id)))  expire = cursor.fetchone()  if datetime.now() gt; datetime.strptime(str(expire['expiration']), "%Y-%m-%d %H:%M:%S"):  embed = discord.Embed(  color = discord.Color.dark_red(),  timestamp = datetime.utcnow()  )  embed.set_author(name="❗️ ERROR ❗️", icon_url="https://c.tenor.com/2gdcdzl-xaoAAAAM/error-computer.gif")  embed.add_field(name="__INFO:__", value=f"Your plan has been removed! Due to expiration.")  embed.set_footer(text="Evil Genios", icon_url="https://cdn.discordapp.com/icons/904638053396672532/643055721178f74ad6a0f1e46843410e.png?size=96")   await message.channel.send(embed=embed)  await asyncio.sleep(5)  with con.cursor() as icursor:  icursor.execute("DELETE FROM `info` WHERE `discord_id`=%s", (message.author.id))  r = icursor.fetchone()  con.commit()  embed1 = discord.Embed(  colour = discord.Color.dark_green(),  timestamp = datetime.utcnow()  )  embed1.set_author(name="❗️ SYSTEM ❗️", icon_url="http://www.happy32.in/images/checkmarksuccess.gif")  embed1.add_field(name="__INFO:__",value=f"`{message.author}`s has been removed!", inline=False)  embed1.set_footer(text="Evil Genios", icon_url="https://cdn.discordapp.com/icons/904638053396672532/643055721178f74ad6a0f1e46843410e.png?size=96")  await message.channel.send(embed=embed1)     # Loads the Cogs and shit @bot.event async def on_ready():  print('loaded!')  for filename in os.listdir("cogs"):  if filename.endswith('.py'):  bot.load_extension(f"cogs.{filename[:-3]}")    # Runs the bot bot.run("")  

Комментарии:

1. expire = cursor.fetchone() ничего не возвращает.

Ответ №1:

Если expire есть None , то expire['expiration'] будет выдано исключение.

Проверьте значение expire , прежде чем делать это.

Комментарии:

1. Спасибо за помощь, добавил чек на истекший срок действия, и теперь он работает.