def OlderNews(MsgObj): #Assigns the users message to a variable so that the appropriate date can be implemented into the URL for searching and returning. chosenDate = MsgObj.msg url = ('https://newsapi.org/v2/everything?' 'q=apples&' 'pageSize=1&' 'from='+chosenDate+'&' 'sortBy=popularity&' 'apiKey=72742ae51f514418a9a6da52faf58be6') #Fetches the data in JSON format. response = requests.get(url).json() specificArticle = response["articles"] #Searches through the JSON of the article that has been requested to find the title, author and url of it. for title in specificArticle: theAcceptedResponseTitle = title["title"] for author in specificArticle: theAcceptedResponseAuthor = author["author"] for url in specificArticle: theAcceptedResponseURL = url["url"] #Adds the title of the article and the author together so it makes grammatical sense when the Discord bot outputs to the user. finalResponse = str(theAcceptedResponseTitle) + " by " + str(theAcceptedResponseAuthor) linkToReponse = ("\nYou can access the article here: " + str(theAcceptedResponseURL)) savedResponse = ("your article from ") + str(chosenDate) #Saves the article that the user just looked at into the JSON file so that next time they visit the bot is able to retrieve this - allows for a more personalised experience between the user and the bot. SaveData(chosenDate, MsgObj.userID, "PreviousViewedArticles") SaveData(savedResponse, MsgObj.userID, "PreviousViewedEntertainment") return finalResponse + linkToReponse
def NewsFromBBC(MsgObj): #Saves the ReplyID to the JSON database so that dialogue can be done on discord. SaveData(NewsScriptGlobal_ID + "_NewsFromBBC", MsgObj.userID, "ReplyID") # This is the BBC News API with our own personal API key. url = " https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=72742ae51f514418a9a6da52faf58be6" #Fetches the data in JSON format. response = requests.get(url).json() specificArticle = response["articles"] #Searches through the JSON of the article that has been requested to find the title, author and url of it. for title in specificArticle: theAcceptedResponseTitle = title["title"] for author in specificArticle: theAcceptedResponseAuthor = author["author"] for url in specificArticle: theAcceptedResponseURL = url["url"] #Adds the title of the article and the author together so it makes grammatical sense when the Discord bot outputs to the user. finalResponse = str(theAcceptedResponseTitle) + " by " + str(theAcceptedResponseAuthor) linkToReponse = ("\nYou can access the article here: " + str(theAcceptedResponseURL)) savedResponse = ("your article!") #Saves the article that the user just looked at into the JSON file so that next time they visit the bot is able to retrieve this - allows for a more personalised experience between the user and the bot. SaveData(savedResponse, MsgObj.userID, "PreviousViewedArticles") SaveData(savedResponse, MsgObj.userID, "PreviousViewedEntertainment") return ("It's okay that you are not sure! Here, have the top article from BBC News") + "\n" + finalResponse + linkToReponse
def EveryTopHeadline(MsgObj): #Sets the category choice to the users so the function can print out the top headline from the current date for that specific category.. categoryChoices = MsgObj.msg #Sets the amount of articles to be printed to 1 so that the user is not bombarded with multiple articles in one go. amountOfArticles = "1" #Gets the top headlines from the UK, 'country=gb' can be changed depending on what country you want to look at. It has been set to UK as it is most likely that the user is an English speaker using this bot in England. url = ('https://newsapi.org/v2/top-headlines?' 'country=gb&' #Can adjust the category depending on what you want specifically, there are only certain categories available: #general, health, science, technology, business, sports, management, entertainment. 'category='+categoryChoices+'&' #Returns a set amount of news articles, default is 20 if a number is not specified and the maximum is 100. 'pageSize='+amountOfArticles+'&' 'apiKey=72742ae51f514418a9a6da52faf58be6') #Gets the URL in JSON format so that specific items can be retrieved later on in the function and allows for simple outputting to the user through the Discord bot. response = requests.get(url).json() specificArticle = response["articles"] #Goes through the JSON in order to retrive the title, author and url of the specific article. for title in specificArticle: theAcceptedResponseTitle = title["title"] for author in specificArticle: theAcceptedResponseAuthor = author["author"] for url in specificArticle: theAcceptedResponseURL = url["url"] ###################################################################################################################################### #The following code was not implemented as there were some issues in being able to retrieve just the name of the article provider. #for source in specificArticle: #theAcceptedResponseSource = source["source"] #for nameOfSource in theAcceptedResponseSource: #theAcceptedResponseName = nameOfSource[0] ###################################################################################################################################### #Adds the title of the article and the author together so it makes grammatical sense when the Discord bot outputs to the user. finalResponse = str(theAcceptedResponseTitle) + " by " + str(theAcceptedResponseAuthor) linkToReponse = ("\n You can access the article here: " + str(theAcceptedResponseURL)) savedResponse = ("your article!") #Saves the article that the user just looked at into the JSON file so that next time they visit the bot is able to retrieve this - allows for a more personalised experience between the user and the bot. SaveData(savedResponse, MsgObj.userID, "PreviousViewedArticles") SaveData(savedResponse, MsgObj.userID, "PreviousViewedEntertainment") return finalResponse + linkToReponse
def authorMostpopular(MsgObj): # Next ONE line by Christian Shaw | Saves the ReplyID to the JSON database so that dialogue can be done on discord. Very important for user input. SaveData(BookScriptGlobal_ID+"_AuthorMostPopular2", MsgObj.userID, "ReplyID") # asks user to input the name of the author #author=input("Please type in the name of the author you would like to search to see their most popular books") return "Please type in the name of the author you would like to search to see their most popular books"
def search_popular(MsgObj): #Next ONE line by Christian Shaw | Saves the ReplyID to the JSON database so that dialogue can be done on discord. Very important for user input. SaveData(FilmScriptGlobal_ID+"_SearchPop2", MsgObj.userID, "ReplyID") #input allows user to choose between what they would like to see return ("Now, you can either see actors(and actresses) or movies. your choice. ")
def top_rated(MsgObj): #Next ONE line by Christian Shaw | Saves the ReplyID to the JSON database so that dialogue can be done on discord. Very important for user input. SaveData(FilmScriptGlobal_ID+"_TopRated2", MsgObj.userID, "ReplyID") #allows user to input a page number return ("what page would you like to go to? ")
def movie_search(MsgObj): # # Next ONE line by Christian Shaw | Saves the ReplyID to the JSON database so that dialogue can be done on discord. Very important for user input. SaveData(FilmScriptGlobal_ID+"_MovieSearch2", MsgObj.userID, "ReplyID") #this inputs the keyword(s) into the search return("please type in the movie title you wish to search for: ")
def bookreview(MsgObj): # Next ONE line by Christian Shaw | Saves the ReplyID to the JSON database so that dialogue can be done on discord. Very important for user input. SaveData(BookScriptGlobal_ID+"_BookReview2", MsgObj.userID, "ReplyID") #isbn =input("Please type in the isbn of a book you would like to see the ratings of") #askes the user to input isbn of the book they want ratings for return "Please type in the isbn of a book you would like to see the ratings of"
def booksearch(MsgObj): # Next ONE line by Christian Shaw | Saves the ReplyID to the JSON database so that dialogue can be done on discord. Very important for user input. SaveData(BookScriptGlobal_ID+"_BookSearch2", MsgObj.userID, "ReplyID") #booktitle=input("Please type in the name of the book you would like to search") #requests user to input a book name return "Please type in the name of the book you would like to search"
def releasedate(MsgObj): # Next ONE line by Christian Shaw | Saves the ReplyID to the JSON database so that dialogue can be done on discord. Very important for user input. SaveData(BookScriptGlobal_ID+"_ReleaseDate2", MsgObj.userID, "ReplyID") #booktitle=input("Please type in the name of the book you want the release date of") #asks the user to input book name they want release date of return "Please type in the name of the book you want the release date of"
def IntroductionToUser(MsgObj): #Saves the ReplyID to the JSON database so that dialogue can be done on discord and referenced from TMDBAPI_DiscordPrototype.py to ensure everything is being consistently called from all files. SaveData(NewsScriptGlobal_ID + "_KeywordsForBranching", MsgObj.userID, "ReplyID") #The beginning response that the bot says to the user so they are aware that they are searching in the News API. Also allows for the user to be aware of what they can search for. beginningResponse = ("So you want to look at some news? Good choice! Unfortunately, I can't read your mind so you might have to help me out here.") + ("\n I can tell you about an article that includes a word of your choice, I can output the top headlines of today, or you can even look into specific categories.") + ("\n So, what would you like to do? (Please use the prefix -r to communicate with me now).") return beginningResponse
def genre_list(MsgObj): # Next ONE line by Christian Shaw | Saves the ReplyID to the JSON database so that dialogue can be done on discord. Very important for user input. SaveData(FilmScriptGlobal_ID+"_GenreList2", MsgObj.userID, "ReplyID") #print("=================================================================================================================================") #used a dict to store possible search queries. more efficient than using an if statement return ("here is a list of genres available: 'Action', 'Adventure', 'Animation', 'Comedy', 'Crime', 'Documentary', 'Drama', 'Family', 'Fantasy', 'History', 'Horror', 'Music', 'Mystery', 'Romance', 'Science Fiction', 'TV Movie', 'Thriller', 'War', and 'Western'.\n Please select one by typing it in: ")
def firstUserInt(MsgObj): # # Next ONE line by Christian Shaw | Saves the ReplyID to the JSON database so that dialogue can be done on discord. Very important for user input. SaveData(FilmScriptGlobal_ID+"_FirstUserInt2", MsgObj.userID, "ReplyID") string = ("I can sort through genres, search for movies, display upcoming, you could also view top rated or even see what is popular/trending at the moment") + ( "\n Please tell me what you would like to see so i can give it to you.") return string
def UserIntro(MsgObj): # Next ONE line by Christian Shaw | Saves the ReplyID to the JSON database so that dialogue can be done on discord. Very important for user input. SaveData(BookScriptGlobal_ID+"_UserIntro2", MsgObj.userID, "ReplyID") #print ("Hello, Welcome to the Book directory. \n I have the ability to provide you with book searches, book reviews/ratings and the release dates of any current or upcoming books and most popular books that an author has.") #UserOption = input("What would you like to see?") # displays the features the chatbot provides to the user and asks them what they want to see return "I have the ability to provide you with book searches, book reviews/ratings and the release dates of any current or upcoming books and most popular books that an author has.\nWhat would you like to see?"
def NaturalReply(WorkXml, Context, MsgObj): from random import randrange # The ISBN opens a different HTML file if Context != "ratings": BookTitle = WorkXml.find("best_book").find("title").text BookID = WorkXml.find("best_book").find("id").text # Saves the recommended film to the json database for later use SaveData(BookTitle, MsgObj.userID, "PreviousViewedBooks") time.sleep(1) SaveData(BookTitle, MsgObj.userID, "PreviousViewedEntertainment") # Creates a list of months so that there is a coherent date instead of numbers Months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] ReleaseDay = WorkXml.find("original_publication_day").text ReleaseMonth = WorkXml.find("original_publication_month").text ReleaseYear = WorkXml.find("original_publication_year").text # This creates the release month from a number to text if the month exists if ReleaseMonth != "": ReleaseMonth = Months[int(ReleaseMonth)-1] RatingNo = WorkXml.find("ratings_count").text # Depending on the context, different things are printed. if Context == "search": Phrase = ["The book you're looking for probably is ", "I found a book called ", "The book you speak of is called "] MainString = (Phrase[randrange(len(Phrase))]+BookTitle+"\nHere's a link to it: "+"https://www.goodreads.com/book/show/"+BookID) elif Context == "date": Phrase = [" released on ", " was published on ", " came out on "] MainString = BookTitle+(Phrase[randrange(len(Phrase))])+ReleaseDay+" "+ReleaseMonth+" "+ReleaseYear elif Context == "ratings": Phrase = [" was rated ", " has been rated ", " got rated "] MainString = ("This book has been rated "+RatingNo+" times.") # Returns the string that was created to that the relevant scripts can return it to the main discord bot to be sent to the user on discord. return MainString # [End of Code by Christian Shaw]
def SpecificNews(MsgObj): chosenTopic = MsgObj.msg SaveData(chosenTopic, MsgObj.userID, "FavNewsTopic") url = ('https://newsapi.org/v2/everything?' # This is the key word that should bring up the relevant article. 'qInTitle='+str(chosenTopic.lower())+'&' 'pageSize=1&' # From what date it should get searched (depending how old you want the article to be) 'from=2019-11-01&' # How to sort the articles (the most popular will show first, therefore, the most relevant and most likely to be in English) 'sortBy=popularity&' 'apiKey=72742ae51f514418a9a6da52faf58be6') #Fetches the data in JSON format. response = requests.get(url).json() specificArticle = response["articles"] #Searches through the JSON of the article that has been requested to find the title, author and url of it. for title in specificArticle: theAcceptedResponseTitle = title["title"] for author in specificArticle: theAcceptedResponseAuthor = author["author"] for url in specificArticle: theAcceptedResponseURL = url["url"] #Adds the title of the article and the author together so it makes grammatical sense when the Discord bot outputs to the user. finalResponse = str(theAcceptedResponseTitle) + " by " + str(theAcceptedResponseAuthor) linkToReponse = ("\nYou can access the article here: " + str(theAcceptedResponseURL)) savedResponse = ("your article on ") + str(chosenTopic) #Saves the article that the user just looked at into the JSON file so that next time they visit the bot is able to retrieve this - allows for a more personalised experience between the user and the bot. SaveData(chosenTopic, MsgObj.userID, "PreviousViewedArticles") SaveData(savedResponse, MsgObj.userID, "PreviousViewedEntertainment") return finalResponse + linkToReponse
def NaturalReply(Dictionary, RandBool, SearchBool, Context, MsgObj): from random import randrange # If the argument given to RandBool was True, then a random film will be taken from the dictionary and assigned to DictData if RandBool == True: RandNo = randrange(len(Dictionary["results"])) DictData = Dictionary["results"][RandNo] # Else, it will be false and will assign the first film from the dictionary to DictData else: DictData = Dictionary["results"][0] # If the SearchBool is True, this shows that the user searched for a film instead of wanted to be recommended one # the phrase list and sentence structure in the mainstring will change accordingly to this. # The context parameter will put in the context where needed to the sentence structure. To provide fluid, natural responses. # Phrases are also randomised, giving a more natural and fluid sounding reply. Less robotic. if SearchBool == True: Phrase = ["Aah, you're looking for is ", "We've found the movie that you're looking for. It's ", "Hmm, I think this is the film you're thinking about is "] MainString = (Phrase[randrange(len(Phrase))]+ DictData['title']+"\n You can find more info here: "+'https://www.themoviedb.org/movie/'+str(DictData['id'])) else: Phrase = ["Well, here's my recommendation of a", "Hmmm, this is a good ", "I think you might like this "] MainString = (Phrase[randrange(len(Phrase))]+Context+" movie. It's called "+DictData["title"]+"\n You can find more info here: "+'https://www.themoviedb.org/movie/'+str(DictData['id'])) # Saves the recommended film to the json database for later use SaveData(DictData["title"], MsgObj.userID, "PreviousViewedFilms") import time time.sleep(1) SaveData(DictData["title"], MsgObj.userID, "PreviousViewedEntertainment") # Returns the string that was created to that the relevant scripts can return it to the main discord bot to be sent to the user on discord. return MainString # [End of Code by Christian Shaw] #firstUserInt()
async def bot(com, *, msg): # [Start of Code by Christian Shaw] Calls the function that creates the message object msgObj = createMsgObj(msg, com.author.id, str(com.author), com.channel) print("User's message >>", msgObj.msg) print("User's message as list >>", msgObj.list) print("User's message's language >>", msgObj.lang) print("User's ID >>", msgObj.userID) print("User's name >>", msgObj.username) print("User's channel >>", msgObj.channel) # Saves the userID and message data to the user_datastore.json file from UserDataManagement import SaveData SaveData(msgObj.userID, msgObj.userID, "UserID") SaveData(str(msgObj.username), msgObj.userID, "Name") SaveData(msgObj.msg, msgObj.userID, "LastMessage") # Calls the function which calls for other scripts to generate replies and returns it as a list botReply = generateReplies(msgObj) # Send's the replies on discord in the order of the botReply list. if len(botReply) != 0: for i in botReply: # Uses the translateText function I created to translate the bot's reply back into the user's language Reply = i #translateText(i, msgObj.lang) await com.send(Reply) else: # If there weren't any replies found to send, it will reply with this: Reply = "Could you try rephrasing what you said? I promise I am doing my best to understand you!" # Uses the translateText function I created to translate the bot's reply back into the user's language Reply = botReply #translateText(Reply, msgObj.lang) await com.send(Reply) #For terminal use only. Creates space between information on the terminal to make it easier to read. print( "\n--------------------------------------------------------------------------" )
def genre_list2(MsgObj): genreDict = {"action": "28", "adventure": "12", "animation": "16", "comedy": "35", "crime": "80", "documentary": "99", "drama": "18", "family": "10751", "fantasy": "14", "history": "36", "horror": "27", "music": "10402", "mystery": "9648", "romance": "10749", "science fiction": "878", "tv movie": "10770", "thriller": "53", "war": "10752", "western": "37"} UserChoice = MsgObj.msg pageNum = 1 # Next ONE line by Christian Shaw | Saves the genre data to json database for use later SaveData(UserChoice, MsgObj.userID, "FavFilmGenre") if type(pageNum) == int: page = pageNum else: page = 1 url = "https://api.themoviedb.org/3/discover/movie?language=en-US&api_key="+api_key+"&with_genres="+str(genreDict[UserChoice.lower()])+"&page="+str(page) #retreives the genre data from server to be used later response = req.get(url) genDict = response.json() # Next ONE line by Christian Shaw | Returns a natural reply using the dictionary data to the discord main script return NaturalReply(genDict, True, False, (MsgObj.msg).lower(), MsgObj)
def SpecificNewsPrimary(MsgObj): #Saves the ReplyID to the JSON database so that dialogue can be done on discord. SaveData(NewsScriptGlobal_ID + "_SpecificNews", MsgObj.userID, "ReplyID") return ("Okay, give me a word or words and I will find you an article that includes it!")
async def r(com, *, reply): msgObj = createMsgObj(reply, com.author.id, str(com.author), com.channel) print("User's reply >>", msgObj.msg) print("User's reply as list >>", msgObj.list) print("User's reply's language >>", msgObj.lang) print("User's ID >>", msgObj.userID) print("User's name >>", msgObj.username) print("User's channel >>", msgObj.channel) # Saves the userID and message data to the user_datastore.json file from UserDataManagement import SaveData SaveData(msgObj.userID, msgObj.userID, "UserID") SaveData(str(msgObj.username), msgObj.userID, "Name") SaveData(msgObj.msg, msgObj.userID, "LastMessage") from UserDataManagement import RetrieveData ReplyID = RetrieveData(msgObj.userID, "ReplyID") Global_ID = "" for char in range(len(ReplyID)): if ReplyID[char] == "_": #ReplyID = Global_ID break Global_ID = Global_ID + ReplyID[char] Local_ID = "" check = False for char in range(len(ReplyID)): if check == True: Local_ID = Local_ID + ReplyID[char] if ReplyID[char] == "_": #ReplyID = Local_ID check = True # This will be the variable that the reply is stored into (must remain empty) BotReply = "" # This part of the code will use the ReplyID to find the correct scripts to use TestScriptGlobal_ID = "0001" NewsScriptGlobal_ID = "1423" FilmScriptGlobal_ID = "6912" BookScriptGlobal_ID = "2151" # This is for the test script if Global_ID == TestScriptGlobal_ID: from Temp_testReply import FindID BotReply = FindID(msgObj, Local_ID) # This is for the news script if Global_ID == NewsScriptGlobal_ID: from NewsAPI import FindID BotReply = FindID(msgObj, Local_ID) # This is for the film script if Global_ID == FilmScriptGlobal_ID: from TMDBAPI_DiscordPrototype import FindID BotReply = FindID(msgObj, Local_ID) # This is for the book script if Global_ID == BookScriptGlobal_ID: from GoodreadsAPI import FindID BotReply = FindID(msgObj, Local_ID) # Next part is going to retrieve and check the "replyID" and go to the required script & function if BotReply == None or BotReply == "": #BotReply = translateText("Sorry, I didn't quite understand that reply", msgObj.lang) await com.send(BotReply) else: #BotReply = translateText(BotReply, msgObj.lang) await com.send(BotReply) #For terminal use only. Creates space between information on the terminal to make it easier to read. print( "\n--------------------------------------------------------------------------" )
def OlderNewsPrimary(MsgObj): #Saves the ReplyID to the JSON database so that dialogue can be done on discord. SaveData(NewsScriptGlobal_ID + "_OlderNews", MsgObj.userID, "ReplyID") return ("Okay, from what date would you like to look at? Please make sure it's from within the past month and in the form YYYY-MM-DD so I can understand you!")
def Reply1(obj): SaveData("0001_0003", obj.userID, "ReplyID") return ("This is the first reply")
def mainDialogue(obj): SaveData("0001_0002", obj.userID, "ReplyID") return "This is the main dialogue"
def EveryTopHeadlinePrimary(MsgObj): #Saves the ReplyID to the JSON database so that dialogue can be done on discord. SaveData(NewsScriptGlobal_ID + "_EveryTopHeadline", MsgObj.userID, "ReplyID") return ("What category would you like to look at for a top headline? The following choices are: general; health; science; technology; business; sports; management; and entertaintment.")