Skip to content
Permalink
master
Switch branches/tags

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?
Go to file
 
 
Cannot retrieve contributors at this time
#-----IMPORTS-----
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!", help_command=None) #sets the prefix for the command and removes the default help message so it can be replaced
from geotext import GeoText
import string
import Process
import asyncio
from dotenv import load_dotenv
load_dotenv()
TOKEN = '' #Discord bot token - DO NOT CHANGE
class DiscordClient(discord.Client):
#-----INITIATION OF BOT-----
async def on_ready(self): #when bot is started, following code is ran
print(f'{self.user} has connected to Discord') #message to console
#changes activity to say "Watching the forecast"
await self.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="the forecast"))
channel = self.get_channel(771302959765127171) #sets channel to send to
await channel.send("Ask me about the weather! (some smaller towns and cities may not be detectable)") #sends message to channel
#-----WHEN A MESSAGE IS DETECTED-----
async def on_message(self,message):
weatherList = ['rain','cloud','weather','forecast','snow',
'sun','wind','temp','humid','pressure','visibility','storm',
'hot','cold','warm'] #a list of keywords
timeList = ['today','morning','afternoon','evening','tonight','monday','tuesday','wednesday','thursday',
'friday','saturday','sunday']
if message.author == self.user: #if the message was sent by the bot itself, the message is ignored
return
theMessage = message.content #assigns the message content to the variable 'theMessage'
theMessage = theMessage.lower()
foundWeatherItem = False
for weatherWord in weatherList: #checks through the list of words and compares to words in the message
if weatherWord in theMessage: #if word was detected...
foundWeatherItem = True #If a keyword is found, set to true
keyword = weatherWord #set the keyword to a variable so it can be passed to Process.py
break
if foundWeatherItem==True:
ID = str(message.author.id) #setting the user's ID
timeWord = None
for timeItem in timeList:
if timeItem in theMessage:
timeWord = timeItem
if timeWord == None:
timeWord = "none"
foundCity = False
def findCity(theMessage):
locationList = []
capitalised = string.capwords(theMessage) #makes the first letter of each word a capital
capitalList = capitalised.split() #splits the users message into a list
for x in range(len(capitalList)): #checks through the list items (individual words)
location = GeoText(capitalList[x]).cities #checks if the current word is a valid location
if len(location)>0: #if a valid location name, foundCity is set to true and the for loop ends
locationList.append(location[0])
return locationList
locationList = findCity(theMessage)
print(locationList)
try: #This section until line 77 adapted from https://github.com/Rapptz/discord.py/blob/master/examples/guessing_game.py
if len(locationList)>0: #Tests if a location is found. If found, foundCity is set to True. If location not found a length can't be found, it'll be a None tyle
foundCity=True
except:
foundCity=False #If a location is not found, set to False
def replyExists(reply):
return reply.author == message.author #Checking if the user submits a location when prompted
if foundCity==False: #If no location is found, user is notified and is asked to type a location
await message.channel.send("Sorry, we couldn't find a location in your message! **Please type a location below.** (note: we might only be able to find larger cities!)")
try:
cityReply = await self.wait_for('message',check=replyExists,timeout=15.0) #Waits for user's reply when prompted
replyMessage = cityReply.content
locationList = findCity(replyMessage)
except asyncio.TimeoutError:
return await message.channel.send("Sorry, you took too long to reply!") #If time elapses without reply, user cannot reply any more
try:
if len(locationList)>0:
foundCity = True
except :
await message.channel.send("Sorry, that wasn't a valid location. Try again later.")
if foundCity==True: #If a location is found, the user is alerted that the weather info is being searched
for newLocation in range(len(locationList)):
toSend = str("Fetching your weather report for "+locationList[newLocation])
await message.channel.send(toSend) #sends to Discord
loc = str(locationList[newLocation]) #location is set to a string to send to Process.py
returnMessage = str(Process.getweather(loc,keyword, timeWord)) #gets weather report message from Process.py
print(timeWord)
outputMessage = "<@"+ID+">, "+returnMessage #adds bold formatting
await message.channel.send(outputMessage) #sends final weather report to Discord
#-----HELP COMMAND-----
@bot.command(name="helpme") #sets the name for the command
async def helpCommand(ctx):
await ctx.send("Ask me about the weather! I accept questions which include the keywords: 'rain','cloud','weather','forecast','snow','sun','wind','temperature','humidity','pressure','visibility' as well as the place name in question.")
client = DiscordClient()
client.run(TOKEN)
#--references--
#https://discordpy.readthedocs.io/en/latest/index.html -- Discord API Reference
#https://realpython.com/how-to-make-a-discord-bot-python/ -- for initial setup of the bot
#https://github.com/Rapptz/discord.py/blob/master/examples/guessing_game.py - Used ideas from this, when city not detected it checks for user input