我在组装一个新的机器人时遇到了极大的困难。我一辈子都无法弄清楚为什么有人尝试对帖子做出反应时程序崩溃。这段代码几乎是从我拥有的可以正常运行的现有bot中剪切并直接粘贴的,没有任何问题。如果有人可以帮助阐明这个令人沮丧的谜团,我将不胜感激。
# insert at 1, 0 is the script path (or '' in REPL)
import sys
sys.path.insert(1,'C:/Users/user/Desktop/Python/wrongbot')
import discord
import asyncio
import random as r
from discord.ext.commands import Bot
from discord.utils import get
from discord import Status
import time
import sqlite3
import csv
import datetime
from datetime import date
import pip
#import gtts
#from gtts import gTTS
from decimal import Decimal
import os
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import emoji
import gosb___main
thePlayers=[]
BOT_PREFIX = ("^")
TOKEN = open("token.ini", "r").read()
dBot = Bot(command_prefix=BOT_PREFIX)
currency_emoji="<:wrongbit:648363628340314152>"
DEFAULT_STATUS="Pancake day is coming!"
DB_NAME = ("sir_wb.db")
#dBot.remove_command('help')
HomeServer=None
HomeServerName="Game Of Silly Battles"
WelcomeChannelName="general-chat"
WelcomeChannel=None
RulesChannelName="welcome-and-rules"
RulesChannel=None
ServerLogChannel=None
ServerLogChannelName="server-log"
theMessage=None
lastRemoval=None
class PlayerClass:#(self,liveboosterid,boostertypeid,setid,coverimage,contents,ownerid)
def __init__(self,userid,wrongbits):
self.UserID=userid
self.WrongBits=wrongbits
async def GetPlayerByUserID(UserID):
global thePlayers
for player in thePlayers:
if str(UserID)==str(player.UserID):
return player
return None
async def WrongbitTransaction(UserID,Amount,Details=""):
print("Process currency")
timestamp = await GetDate2()+"-"+await GetTime()
conn = sqlite3.connect(DB_NAME)
c = conn.cursor()
c.execute("INSERT INTO tblCurrency (UserID,Amount,Notes,TimeStamp) VALUES ("+chr(34)+str(UserID)+chr(34) + ", "+str(Amount)+", "+chr(34)+str(Details)+chr(34) +", "+chr(34)+str(timestamp)+chr(34) +");")
conn.commit()
conn.close()
#global thePlayers
player=await GetPlayerByUserID(UserID)
player.Wrongbits+=Amount
async def GetCurrentWrongbits(UserID):
print("get currency total for player")
conn = sqlite3.connect(DB_NAME)
c = conn.cursor()
c.execute("SELECT Sum(tblCurrency.Amount) from tblCurrency where UserID="+chr(34)+str(UserID)+chr(34) +";")
conn.commit()
conn.close()
async def GetMemberByUserID(UserID):
global HomeServer
for member in HomeServer.members:
if str(member.id)==str(UserID):
return member
return None
async def SyncMemberList():
print("Synchronising member list")
global HomeServer
global thePlayers
botMembers1=[]
dbMembers1=[]
botMembers2=[]
dbMembers2=[]
conn = sqlite3.connect(DB_NAME)
c = conn.cursor()
c.execute("SELECT * FROM tblMembers;")#[UserID,Name,DisplayName]
lstThis=c.fetchall()
for row in lstThis:
dbMembers1.append(str(row[0]))
dbMembers2.append(str(row[0]))
for member in HomeServer.members:
botMembers1.append(str(member.id))
botMembers2.append(str(member.id))
#------check for new members
for UserID in dbMembers1:
try:
botMembers1.remove(UserID)
except ValueError:
print("value error checking for new members")
if len(botMembers1)>0:
for UserID in botMembers1:
member= await GetMemberByUserID(UserID)
bFound=False
for player in thePlayers:
if str(member.id)==str(player.UserID):
bFound=True
if not bFound:
print("adding member "+str(member.display_name)+" to db")
c.execute("INSERT INTO tblMembers (UserID,Name,DisplayName) VALUES ( "+ str(chr(34)) + str(UserID)+ str(chr(34)) +", "+ str(chr(34)) + str(member.name) + str(chr(34)) +", "+ str(chr(34)) + str(member.display_name) + str(chr(34)) + ");")#[UserID,Name,DisplayName]
conn.commit()
thePlayers.append(PlayerClass(member.id,0))
await WrongbitTransaction(member.id,1000,"Initialiser")
print("added "+str(len(botMembers1))+" new members to database")
#------check for left members
for UserID in botMembers2:
try:
dbMembers2.remove(UserID)
except ValueError:
print("value error checking for new members")
if len(dbMembers2)>0:
for UserID in dbMembers2:
c.execute("SELECT * FROM tblMembers WHERE UserID="+ str(chr(34)) + str(UserID)+ str(chr(34)) +";")
lstMemberDetails=c.fetchall()
if len(lstMemberDetails)>0:
print("deleting left member "+str(lstMemberDetails[0][2])+" from db")
c.execute("DELETE FROM tblMembers WHERE UserID="+ str(chr(34)) + str(UserID)+ str(chr(34)) +";")
c.execute("DELETE FROM tblDaysProspecting WHERE UserID="+ str(chr(34)) + str(UserID)+ str(chr(34)) +";")
conn.commit()
print("removed "+str(len(dbMembers2))+" left members from database")
conn.close()
async def GetTime():
currentDT = datetime.datetime.now()
tHours=str(currentDT.hour)
tMins=str(currentDT.minute)
tSecs=str(currentDT.second)
if len(tHours)==1:
tHours="0"+tHours
if len(tMins)==1:
tMins="0"+tMins
if len(tHours)==1:
tSecs="0"+tSecs
tTime=str(tHours)+":"+str(tMins)+":"+str(tSecs)
return tTime
async def GetDate():
currentDT = datetime.datetime.now()
dDay=str(currentDT.day)
dMonth=str(currentDT.month)
if len(dDay)==1:
dDay="0"+dDay
if len(dMonth)==1:
dMonth="0"+dMonth
dYear=currentDT.year
dDate=str(dDay)+"/"+str(dMonth)+"/"+str(dYear)
return dDate
async def GetDate2():
currentDT = datetime.datetime.now()
dDay=str(currentDT.day)
dMonth=str(currentDT.month)
if len(dDay)==1:
dDay="0"+dDay
if len(dMonth)==1:
dMonth="0"+dMonth
dYear=currentDT.year
dDate=str(dYear)+"-"+str(dMonth)+"-"+str(dDay)
return dDate
async def GetTimeNumber(strTime):
timeSplit = strTime.split(":")
return( (int(timeSplit[0])*60) + (int(timeSplit[1])) )
async def CheckIsTime(strTime="00:00"):
curTime=round(time.time())
nowTime= await GetTime()
triggerNumber =await GetTimeNumber(strTime)
nowNumber = await GetTimeNumber(nowTime)
if nowNumber==triggerNumber and nowNumber<=(triggerNumber+2) :#2 mins grace
return True
return False
async def GetVersion():
return str(os.path.basename(__file__)).lower().replace("sir_wrongbot_","").replace(".py","").replace("_",".")
async def LoadServers():
global WelcomeChannel
global WelcomeChannelName
global HomeServer
global HomeServerName
global RulesChannel
global RulesChannelName
global ServerLogChannel
global ServerLogChannelName
for server in dBot.servers:
print("Logged in to " + server.name)
# if server.name=="Night Watch Trading":
# await dBot.leave_server(server)
# print("left blank server")
HomeServer = await GetServerByName(HomeServerName)
WelcomeChannel = await GetChannelByName(WelcomeChannelName)
RulesChannel= await GetChannelByName(RulesChannelName)
ServerLogChannel= await GetChannelByName(ServerLogChannelName)
async def SendEmbed(channel,Title,content):
e=discord.Embed(title=Title, color=0xbdf488,description=content)
await dBot.send_message(channel,"",embed=e)
async def SWBEmbed(dBot,channel,title,content,url=None):
chunks=[]
thisChunk=""
endLine=False
splitContent=content.split("\n")
for word in splitContent:
if len(thisChunk) + len(word) +1 <=1950:
thisChunk+=word+"\n"
endLine=False
else:
chunks.append(thisChunk)
thisChunk=word+"\n"
endLine=True
if thisChunk!="":
chunks.append(str(thisChunk))
x=0
for chunk in chunks:
x+=1
if x%5==0:
await asyncio.sleep(1)
e=discord.Embed(title=title, color=0xbdf488,description=chunk)
if url!=None:
e.set_thumbnail(url=url)
await dBot.send_message(channel,"", embed=e)
async def GetRulesMessage():
#thisChannel=await GetChannelByName("rules")
async for message in dBot.logs_from(RulesChannel, limit=500):
#print("MESSAGE: \n"+message.content+"\n____________ in "+RulesChannel.server.name)
if "agree to these rules, click the" in message.content.lower():
print("found access message")
return message
print("not found access message")
return None
async def GiveMemberRoleByName(Member,RoleName):#returns false if failed,
pisscunt = dBot.servers
for server in pisscunt:
#print("SEARCHING "+server.name+ " for " + RoleName)
#print("match member " + Member.display_name + " id " + Member.id)
for member in server.members:
#print("found member " + member.display_name + " id " + member.id)
if member.id==Member.id:
#print("SUCCESS Found : "+Member.display_name)
if RoleName.lower() in [y.name.lower() for y in server.roles]:
#print("server has role")
if RoleName.lower() not in [x.name.lower() for x in member.roles]:
#print("member does not have role")
for role in server.roles:
if RoleName.lower() in role.name.lower():
if " name" in RoleName.lower():
#print("wants colour")
oldRole = None
for nRole in member.roles:
if " name" in nRole.name.lower():
print("already has colour")
print("removing "+nRole.name)
await dBot.remove_roles(member,nRole)
await dBot.add_roles(member,role)
print(Member.name + " added role : " + RoleName)
return True
return False
async def RemoveMemberRoleByName(Member,RoleName):#returns false if failed,
global HomeServer
for server in dBot.servers:
#print("server: "+server.name)
print(Member.name + " removed role : " + RoleName)
for member in server.members:
if member.id==Member.id:
#print("found member")
if RoleName.lower() in [y.name.lower() for y in server.roles]:
#print("srver has role")
if RoleName.lower() in [x.name.lower() for x in member.roles]:
#print("member has role")
for role in server.roles:
if RoleName.lower() in role.name.lower():
#print("found role")
await dBot.remove_roles(member,get(server.roles, name=RoleName))
#print("removed role")
return True
async def GetMemberFromUser(user):
for server in dBot.servers:
for member in server.members:
if member.id==user.id:
return member
return None
async def GetMemberByUserID(userid):
for server in dBot.servers:
for member in server.members:
if member.id==userid:
return member
return None
async def GetChannelByID(channelid):
global HomeServer
output=None
for channel in HomeServer.channels:
if channel.id==channelid:
output=channel
return output
async def GetChannelByName(channelName):
#for server in dBot.servers:
for channel in HomeServer.channels:
if str(channel.name) == str(channelName):
return channel
async def GetServerByName(serverName):
for server in dBot.servers:
if server.name == serverName:
return server
async def CheckDisplayName(message,members,displayName):
bPresent=None
if displayName[:2]=="<@":
thisName = "<" + displayName[-(len(displayName)-2):]
else:
thisName=displayName
for theMember in members:
if (thisName.casefold() in theMember.display_name.casefold()) or (theMember.mentioned_in(message)):
bPresent=theMember.display_name
return bPresent
async def CheckProspectDays(member):
global ServerLogChannel
conn = sqlite3.connect(DB_NAME)
c = conn.cursor()
c.execute("SELECT * FROM tblDaysProspecting WHERE UserID="+chr(34)+str(member.id)+chr(34)+";")
lstMember=c.fetchall()
warnings=None
txtMsg=""
if len(lstMember)==0:# never warned
warnings=0
else: #multiple warnigns
warnings=int(lstMember[0][1])
if warnings!=3:
txtMsg="Hello there "+member.display_name+",\nJust a quick note from I Haz Warez home. It seems you haven't read and accepted the server rules yet. You will not have access to the rest of the server until you have agreed to the rules sorry.\nThanks :heart:"
await SendEmbed(member,"Server Membership Update:",txtMsg)
if warnings==0:
c.execute("INSERT INTO tblDaysProspecting (UserID,Days) VALUES ( " +chr(34)+ str(member.id) +chr(34)+ ", 1);")
else:
c.execute("UPDATE tblDaysProspecting SET Days="+ str(warnings+1) +" WHERE UserID="+chr(34)+ str(member.id)+chr(34)+";")
conn.commit()
await dBot.send_message(ServerLogChannel,member.display_name+" was given prospect warning #"+str(warnings+1)+".")
print("warning #"+str(warnings+1)+" for "+member.display_name)
else: #too many warnigns
txtMsg="Hey "+member.display_name+",\nI'm sorry to see that after several days you still have not accepted the server rules.\nYou have now been removed from the server. We hope to see you again soon.\nThanks :heart:"
await SendEmbed(member,"Removal From Server:",txtMsg)
await dBot.send_message(ServerLogChannel,member.display_name+" was kicked for not accepting the rules.")
await dBot.kick(member)
print("auto kicked "+member.display_name)
conn.close()
async def Main_Loop(interval):
#game loop start
global lastRemoval
while True:
if await CheckIsTime("9:06") and str(lastRemoval)!=str(await GetDate()):
print("prospect remover triggered")
lastRemoval=await GetDate()
for member in HomeServer.members:
if "prospect" in [y.name.lower() for y in member.roles]:
await CheckProspectDays(member)
await asyncio.sleep(interval)#pause
async def IsMemberAdmin(member,channel):
permissions=channel.permissions_for(member)
return permissions.administrator
async def PrepContext(ctx):
message=ctx.message
#print(message)
channel=message.channel
#print(channel)
server=message.server
#print(server)
return message,channel,server
#----------------------------COMMANDS
#----------------------------EVENTS
@dBot.event
async def on_ready():
await dBot.change_presence(game=discord.Game(name="Initialising....."))
print("Logged in as " + dBot.user.name)
await LoadServers()
global theMessage
await SyncMemberList()
theMessage = await GetRulesMessage()
dBot.messages.append(theMessage)
#print(RulesChannel.name)
#global theChannel
await dBot.change_presence(game=discord.Game(name=DEFAULT_STATUS))
#dBot.loop.create_task(Main_Loop(1)) # loop for timer
@dBot.event
async def on_member_join(member):
global thePlayers
bFound=False
for player in thePlayers:
if str(member.id)==str(player.UserID):
bFound=True
print(member.display_name+" joined the server")
await GiveMemberRoleByName(member,"Prospect")
txtMsg="**Welcome"
if bFound:
txtMsg+=" back"
txtMsg+=" to our stupid server "+str(member.display_name)+"!**\n\nPlease make yourself comfortable here at Game Of Silly Battles. I am Sir Wrongbot The Homonculus, and I help make things work around here.\n**Please note that new members will have to read and agree to the server rules before being allowed access to the rest of the server.**\n\nThank you, and please enjoy using Game Of Silly Battles."
await SendEmbed(member,"Welcome to Game Of Silly Battles",txtMsg)
await SyncMemberList()
@dBot.event
async def on_member_remove(member):
print(member.display_name+" left the server")
welcome=["Later then #NAME#.","It saddens me that #NAME# has returned to the Hist.","As mud as my mother! #NAME# has left us.","May the rains be ever on your back #NAME#.","#NAME# has left, it dries my scales!","Sithis has called #NAME# back to the void.","By seed and spleen! The dryskin #NAME# has left."]
txtMsg=r.choice(welcome).replace("#NAME#",member.mention)
global WelcomeChannel
await SendEmbed(WelcomeChannel,"Member Left:","**"+txtMsg+"**")
await SyncMemberList()
#await dBot.send_message(WelcomeChannel,txtMsg)
# @dBot.event
# async def on_reaction_add(reaction, user):
# #print(reaction.emoji)
# print("tits")
# try:
# channel=reaction.message.channel
# message=reaction.message
# member= await GetMemberByUserID(user.id)
# if "cuffs" in [y.name.lower() for y in member.roles]:
# print("removed react")
# await dBot.remove_reaction(message=reaction.message,emoji=reaction.emoji,member=user)
# #await reaction.remove(user)
# return
# print("got user id")
# if "bots" in [y.name.lower() for y in user.roles]:
# return
# print("not a bot")
# if "rules" in channel.name:
# print("rules channel")
# if str(reaction.emoji)=="<:i_haz_warez:613687888890167307>":
# print("right emoji")
# if str(message.content)==str(theMessage.content):
# print("right message")
# if "player" not in [y.name.lower() for y in member.roles]:
# print("not already in server")
# if "prospect" in [y.name.lower() for y in member.roles]:
# print("already in limbo")
# print("add role")
# #await GiveMemberRoleByName(member,"spring surprise")
# await dBot.add_roles(member, get(HomeServer.roles, name="Player"))
# await asyncio.sleep(1)
# print("remove role")
# await dBot.remove_roles(member, get(HomeServer.roles, name="Prospect"))
# #await RemoveMemberRoleByName(member,"limbo")
# #introduce
# welcome=["Welcome #NAME# dryskin. May the Hist embrace you.","I extend the claw of greeting #NAME#.","Sun on my scales! #NAME# has joined us.","Welcome #NAME#, my nest is yours.","#NAME# has arrived, like cool rain on my scales.","Truly we are sun-blessed, #NAME# is here!","By my egg! The softskin #NAME# is here."]
# txtMsg=r.choice(welcome).replace("#NAME#",member.mention)
# global WelcomeChannel
# await SendEmbed(WelcomeChannel,"Member Joined:","**"+txtMsg+"**")
# #await dBot.send_message(WelcomeChannel,txtMsg)
# except :
# error= sys.exc_info()[0]
# print(error)
@dBot.event
async def on_message(message):
if message.author == dBot.user:
return
if "cuffs" in [y.name.lower() for y in message.author.roles]:
await dBot.delete_message(message)
return
await dBot.process_commands(message)#neccessary to allow commands and on_message to fire on the same bot
#-------------RUN!
dBot.run(TOKEN)
如您所见,我已经完全注释掉了on_reaction事件处理程序,这似乎无关紧要。拜托,我到底在这里想念什么?