import discord
import os # To get token into our main code file we use os library
import requests #makes http requests to get data in our case we get data from our API
import json # API returns json
import random # we use this for randomising inspiretion when user sends sad messages.
from replit import db # we use this to access repel.it's data base
client = discord.Client() #instance to client it is connection to discord
# bellow is the function to genrate random new quotes with author name
sad_words = ["sad", "depressedfrom replit import db", "unhappy", "miserable"]
Cheer_up = [" Whoever is trying to bring you down, is already below you","You are awesome! Never forget that", "Forget what’s gone, appreciate what remains, and look forward what’s coming next"]
if "responding" not in db.keys(): #We create a new key in the database called "responding" and set it to "True". We'll use this to determine if the bot should respond to sad words or not.
db["responding"] = True
#we only create the new key if it doesn't already exist.
def get_quote():
response = requests.get("https://zenquotes.io/api/random") # use to genrate random quotes
json_data = json.loads(response.text) # Converting this response to json
quote = json_data[0]['q'] + " " + json_data[0]['a'] # Here we are getting quotes from json in above line we loaded it here by ['q'] we get quotes and then we concatenate it with name of the author of the quote.
return (quote)
def update_cheer_ups(cheering_up_message): # We are creating the function for udating encouragements.
if "encouragements" in db.keys(): #Check if encouragements is key in the database
encouragements = db["encouragements"]
encouragements.append(cheering_up_message) # adding new engcouragements to list
db["encouragements"] = encouragements # updated encoragements to our data base of repl
else:
db[encouragements] = [cheering_up_message] # if there would not be any encouragements in database we will have to create it
def delete_cheer_ups(index): #this function is for deleting cheeeing messages we require index for deleting cheering up messages
encouragements = db["encouragements"] # Getting list of cheering up message messages from data base
if len(encouragements) > index: # Check if entered index value is valid for getting message index should be > message
del encouragements[index] # deleteing the cheering message
db["encouragements"] = encouragements # updated to database with changes
@client.event #register an event
# This library has lots of events
# This library is asyncrones library so this works on call back function
# Call back function means it occurs only when somthing occurs in our case
# Program bellow has on_ready & on_message are events
# This events makes the call back function run
async def on_ready(): # Called when bot is ready to get used
print("we have logged in as {0.user}".format(client))
# Here we are replacing 0 wiht client to get user
@client.event # agian registering the event before any other is called
async def on_message(message): # This is called when bot recives any message
msg = message.content
if msg == client.user: # we have to make sure that we ignore messages from ourselves. We do this by checking if the Message.author is the same as the Client.user.
return
if msg.startswith('inspire!'): # When someone uses the command $hello then our bot sends the message which is below
quote = get_quote()
await message.channel.send(quote)
options = Cheer_up
if db["responding"]: #section that responds to sad words is now inside this if statement
options = Cheer_up
if "encouragements" in db.keys():
options = options + db["encouragements"]
if "encouragements" in db.keys():
options = options + db[encouragements]
if msg.startswith('hello!'): # When someone uses the commad $hello then our bot sends the message which is bellow
await message.channel.send('Hello welcome to my server')
if any(word in msg for word in sad_words): # Here we are we created that id anyone writes sad word from list of sad words our bot will cheer user by taking quotes from Cheer_up.
await message.channel.send(random.choice(options))
if msg.startswith("new!"): # Command to add new message to data base
cheering_up_message = msg.split("new! ", 1)[1] # here we store message afte new! command to data base here we get every thing in array so we use [1] to call message because message would be 2nd element of array
update_cheer_ups(cheering_up_message) # Updating message which is given by user
await message.channel.send("New encouraging message learn't") # just letting user know that his given encoraging message is stored
if msg.startswith("del!"):
encouragements = [] # First a new variable called encouragements is initialized as an empty array. The reason for this is that this section of code will send a message with an empty array if the database does not include an "encouragement" key.
if "encouragements" in db.keys(): # checking if encouragement key exist's
index = int(msg.split("$del",1)[1]) #If the "encouragement" key is in the database, the index will be split off from the Discord message starting with "$del"
delete_encouragment(index) # Then, the delete_encouragement() function is called passing in the index to delete.
encouragements = db["encouragements"] # he updated list of encouragements is loaded into the encouragements variable, and then the bot sends a message to Discord with the current list.
await message.channel.send(encouragements)
if msg.startswith("$list"):
encouragements = []
if "encouragements" in db.keys():
encouragements = db["encouragements"]
await message.channel.send(encouragements)
if msg.startswith("$responding"):
value = msg.split("$responding ",1)[1]
if value.lower() == "true":
db["responding"] = True # The bot will only respond to sad words if it is true like in this line right here. The ability to update this value comes after this next section.
await message.channel.send("Responding is on.")
else:
db["responding"] = False
await message.channel.send("Responding is off.")
client.run(os.getenv('TOKEN'))
# This client.run is to run the bot we put our bot's token which is genrated during it's creation.
# Token acts as password of bot it should not been shared
# we did not pasted token here because in repl.it we creat .env extinsion file to make our token hidden
# os.getenv is used to access the token from env file
# it not nessury to use TOKEN it just like variable
# when we are doing this localy we do not need .env file to use token we can normaly paste token here in repl we are doing publical that is why it is env and os to access token from env.
答案 0 :(得分:0)
在第 28 行访问 db
的键 'encouragements'
时,您似乎遗漏了引号:
db['encouragements'] = [cheering_up_message]