Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Chatbot/Chatbot.py
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
150 lines (121 sloc)
7.93 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#==============This code was written by Emily================== | |
# This section of code was adapted from https://realpython.com/how-to-make-a-discord-bot-python/#creating-a-discord-connection by Emily | |
import os | |
import random | |
import discord | |
import steam | |
import requests | |
from steam.webapi import WebAPI | |
from dotenv import load_dotenv #only used so we can have the token outside of the source code | |
from steam.steamid import * | |
load_dotenv() | |
TOKEN = os.getenv('DISCORD_TOKEN') | |
GUILD = os.getenv('DISCORD_GUILD') | |
steamApiKey = os.getenv('STEAM_API_KEY') | |
client = discord.Client() | |
api = WebAPI(key=steamApiKey) | |
#==================DEFINITIONS GO HERE================== | |
steamID= "STEAM_0:0:73873614" #this is Emily's steamID which is useful to use as a stub when testing | |
def steamAchievementPercentages(steamID, gameID): #Emily - as you can see it's going well | |
achieveList= requests.get("http://api.steampowered.com/ISteamUserStats/GetPlayerAchievements/v0001/?appid=" +gameID+ "&key=" +steamApiKey+ "&steamid=" +steamID) | |
totalAchieves = 0 | |
achievesCompleted = 0 | |
achieveList = achieveList.text | |
achieveList = achieveList.replace("\"", " ") | |
achieveList = achieveList.replace("},{", "-") | |
achieveList = achieveList.strip("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz,:0123456789\" {}") | |
achieveList = list(achieveList.split("-")) | |
print (achieveList) | |
for achieve in achieveList: | |
if "achieved :0" in achieve: | |
totalAchieves = totalAchieves + 1 | |
if "achieved :1" in achieve: | |
achievesCompleted = achievesCompleted + 1 | |
totalAchieves = totalAchieves + 1 | |
if totalAchieves > 0: | |
percentage= round ((achievesCompleted/totalAchieves)*100, 2) | |
return percentage | |
else: | |
return 0 | |
#print (steamAchievementPercentages("76561198108012956", "582010")) | |
#print (steamAchievementPercentages("76561198047733265", "582010")) | |
#==================END OF DEFINITIONS=================== | |
@client.event #Prints in the terminal if bot connects successfully | |
async def on_ready(): | |
print(f'{client.user} has connected to Discord!') | |
for guild in client.guilds: | |
if guild.name == GUILD: | |
break | |
print( f'{client.user} is connected to the following guild:\n' | |
f'{guild.name}(id: {guild.id})') | |
members = '\n - '.join([member.name for member in guild.members]) | |
print(f'Guild Members:\n - {members}') | |
polls = {} # masud added this to hold poll data. Can be switched to a database in the future | |
@client.event | |
async def on_message(message): #checks for a message | |
if message.author == client.user: #makes sure it's a user | |
return | |
greetings = ["hello", "howdy", "hey",] #Says hello (creepily) to the user if they use a greeting word | |
greetCheck = [entry for entry in greetings if(entry in message.content.lower())] #This line is adapted from https://www.geeksforgeeks.org/python-test-if-string-contains-element-from-list/ by Emily | |
if greetCheck: | |
creepyHellos =["Why hello there, I am awakening from my slumber", | |
"My child I am learning, hi", | |
"I was enjoying the void before you woke me, I guess it's polite to say hello", | |
"Like life, my sleep was short. Hello child", | |
"Hello, what do you need me for this time?", | |
"Howdy y'all- yeah that wasn't working for me either. What can I do?",] | |
response = random.choice(creepyHellos) | |
await message.channel.send(response) | |
# ================================================ | |
# ================ Masud did this ================ | |
if "salt " == (message.content.lower())[:5]: # checks if the input matches "salt " | |
communityName = (message.content)[5:] # saves the rest of the input as communityName | |
if communityName.upper() in polls.values(): # if there is a poll active already | |
pollID = list(polls.keys())[list(polls.values()).index(communityName.upper())] # get the ID of the poll | |
await message.channel.send(f'The community: {communityName} already has a poll active. Poll ID:{pollID}.') # message to discord | |
else: # and if there is not an active poll already... | |
poll = await message.channel.send(f'vote here for {communityName}:') # create the vote poll | |
# print(f'[BOT DEBUG] {communityName} added to list of polls') # print to console for debugging only | |
polls[poll.id] = communityName.upper() # save the pollID and communityName together | |
# print("[BOT DEBUG] Poll dict:\n",polls) # print list of polls active for debugging only | |
await poll.add_reaction("✅") # add the tick emoji for the poll | |
await poll.add_reaction("❌") # add the cross emoji for the poll | |
if "count " == (message.content.lower())[:6]: # checks if the input matches "count ". DevOps work item 33 | |
communityName = (message.content)[6:] # saves the rest of the input as communityName | |
if communityName.upper() not in polls.values(): # checks if the poll does not exist already | |
await message.channel.send(f'No poll found for community: {communityName}.') # messages to discord | |
else: # if the poll does exist ... | |
pollID = list(polls.keys())[list(polls.values()).index(communityName.upper())] # get the pollID with the matching communityName | |
pollMessage = await message.channel.fetch_message(pollID) # get the message object with the pollID | |
pollReactions = pollMessage.reactions # accesses the reactions for the pollMessage object | |
await message.channel.send(f'Here are the saltiness statistics for the community {communityName}\nPoll ID:{pollID}') # message to discord | |
countEmbed = discord.Embed() # Discord embed object | |
countDesc = "" # description of countEmbed object | |
countEmbed.title = f"Is the community {communityName} salty or supportive?" # title of countEmbed object. DevOps work item 32 | |
tickCount = 0 | |
crossCount = 0 | |
for emj in pollReactions: # for each emoji in the reactions object | |
emojiCount = emj.count - 1 # remove 1 vote, which was from the bot. | |
# print("[BOT DEBUG] emj.emoji:",emj.emoji) # debug code for reactions.emoji object | |
if emj.emoji == "✅": # if emoji is tick emoji | |
tickCount = emj.count - 1 # this reaction will be tickCount | |
elif emj.emoji == "❌": # if emoji is cross emoji | |
crossCount = emj.count - 1 # this reaction will be crossCount | |
if emojiCount == 1: # adjust embed description accordingly | |
countDesc = countDesc + f'\n{emj.emoji} : {emojiCount} vote' | |
else: | |
countDesc = countDesc + f'\n{emj.emoji} : {emojiCount} votes' | |
# add a message to the end of the results depending on the votes for the emojis. DevOps work item 34 | |
# print("[BOT DEBUG] tick cross :",tickCount,crossCount) # this code was used to debug the tick and cross counts. | |
if tickCount == crossCount: | |
countDesc = countDesc + "\n This community seems to be equally supportive and salty." | |
elif tickCount > crossCount: | |
countDesc = countDesc + "\n This community seems to be more supportive." | |
elif tickCount < crossCount: | |
countDesc = countDesc + "\n This community seems to be more salty." | |
# add the description to the embed and message it to the channel. | |
countEmbed.description = countDesc # add embed description to embed | |
await message.channel.send(embed=countEmbed) # send the embed to the channel the message is in | |
# ================ up to about here ================ | |
client.run(TOKEN) #this is the token of the discord bot. You can create your own bot and put that token in here or the .env file to run the code | |
#================================ |