Python 如何从列表中删除报价?
我正在为我的一个朋友制作一个Python 如何从列表中删除报价?,python,bots,discord,discord.py,Python,Bots,Discord,Discord.py,我正在为我的一个朋友制作一个discord.pybot。我想这样做,你可以添加愚蠢的报价列表,然后有他们随机选择。我已经完成了这么多 然而,我也希望能够删除不相关的引用、错误的引用等。我想知道如何才能做到这一点 以下是到目前为止我得到的信息: import discord from discord.ext.commands import Bot from discord.ext import commands import random import pickle import os Clie
discord.py
bot。我想这样做,你可以添加愚蠢的报价列表,然后有他们随机选择。我已经完成了这么多
然而,我也希望能够删除不相关的引用、错误的引用等。我想知道如何才能做到这一点
以下是到目前为止我得到的信息:
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import random
import pickle
import os
Client = discord.Client()
bot_prefix = "."
bot = commands.Bot(command_prefix=bot_prefix)
@bot.event
async def on_ready():
print("Bot Online!")
print("Name: {}".format(bot.user.name))
print("ID: {}".format(bot.user.id))
class Main_Commands():
def __init__(self, bot):
self.bot = bot
# .addquote
@bot.command(pass_context = True)
async def addquote(ctx, *answer):
answer=" ".join(answer)
if not os.path.isfile("quote_file.pk1"):
quote_list = []
else:
with open("quote_file.pk1", "rb") as quote_file:
quote_list = pickle.load(quote_file)
quote_list.append(answer)
with open("quote_file.pk1", "wb") as quote_file:
pickle.dump(quote_list, quote_file)
await bot.say('Quote: "{}" added!'.format(answer))
# .quote
@bot.command(pass_context = True)
async def quote(ctx):
with open("quote_file.pk1", "rb") as quote_file:
quote_list = pickle.load(quote_file)
await bot.say(random.choice(quote_list))
bot.run("TOKEN")
基本上,我想添加另一个函数,
.removequote()
,该函数可以删除特定的引号,同时保持其他引号的完整性。remove quotes与add quote非常相似,只需替换一行。使用列表comp而不是.append来过滤掉不需要的报价。其他一切都可以保持不变
# .removequote
@bot.command(pass_context = True)
async def removequote(ctx, *answer):
answer=" ".join(answer)
if not os.path.isfile("quote_file.pk1"):
quote_list = []
else:
with open("quote_file.pk1", "rb") as quote_file:
quote_list = pickle.load(quote_file)
# This line:
quote_list = [quote for quote in quote_list if quote != answer]
with open("quote_file.pk1", "wb") as quote_file:
pickle.dump(quote_list, quote_file)
await bot.say('Quote: "{}" deleted!'.format(answer))
对于每台服务器的pickle,您可以为每台服务器使用不同的文件名,或者为pickle使用dict(就个人而言,我认为存储在单独的文件中更有效,因为您不必加载其他服务器的引号):
谢谢有没有办法为每台服务器创建一个单独的列表?@根据消息来自哪个服务器创建单独的pickle文件,或者将信息存储在某种数据库中(并将原始服务器位置信息与报价本身一起存储)。
# .removequote
@bot.command(pass_context = True)
async def removequote(ctx, *answer):
answer=" ".join(answer)
filename = "quote_file_{}.pkl".format(ctx.message.server.id)
if not os.path.isfile(filename):
quote_list = []
else:
with open(filename, "rb") as quote_file:
quote_list = pickle.load(quote_file)
quote_list = [quote for quote in quote_list if quote != answer]
with open(filename, "wb") as quote_file:
pickle.dump(quote_list, quote_file)
await bot.say('Quote: "{}" deleted!'.format(answer))