【问题标题】:discord.py 'NoneType' Object is not subscriptablediscord.py 'NoneType' 对象不可下标
【发布时间】:2022-01-12 18:22:42
【问题描述】:

我在if datetime.now() > datetime.strptime(str(expire['expiration']), "%Y-%m-%d %H:%M:%S"): 收到错误,因为“NoneType”对象不可订阅,好吧,我在 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() >  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() >  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("")

【问题讨论】:

  • expire = cursor.fetchone() 没有返回任何内容。

标签: python discord discord.py


【解决方案1】:

如果expireNone,那么expire['expiration'] 将抛出异常。

在做之前检查expire的值。

【讨论】:

  • 感谢帮助,添加了过期检查,现在可以使用了。
猜你喜欢
  • 2020-11-06
  • 2013-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-10
  • 2015-01-23
相关资源
最近更新 更多