Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
One of the first "working" pieces of code I wrote in python for discord ft. global variables
async def cmd_weather(self, channel, author):
import json
from array import array
import requests
from collections import OrderedDict
from pprint import pprint
api_key = "&APPID=507e30d896f751513350c41899382d89"
city_name_url = ""
units = "&units=metric"
global general_info
general_info = {
"Humidity (%)": 0,
"Pressure": 0,
"Temperature(C)": 0,
"Max. Temp.(C)": 0,
"Min. Temp.(C)": 0
def connectapi():
global parsed
global data
global urlrequest
urlrequest = city_name_url + str_city_input + units + api_key
response = requests.get(urlrequest)
content = json.loads(response.text)
data = json.loads(content.decode('utf8'), object_pairs_hook=OrderedDict)
parsed = json.dumps(data, indent=4, sort_keys=True)
return content
def find_data():
global country_name
global city_name
global general_info
global weather_description
global formatted_general_info
city_name = data['name']
country_name = str(data['sys']['country'])
for key, value in data['main'].items():
if key == "humidity":
general_info['Humidity (%)'] = value
elif key == "pressure":
general_info['Pressure'] = value
elif key == "temp":
general_info['Temperature(C)'] = value
elif key == "temp_max":
general_info['Max. Temp.(C)'] = value
elif key == "temp_min":
general_info['Min. Temp.(C)'] = value
def formatlines():
global innerlines
global formatted_general_info
innerlines = '\n'.join('%s:%s' % (k, v) for k, v in general_info.items())
formatted_general_info = (str(innerlines).replace("{", "").replace("}", ""))
return """ \
\t\t %s
\t\t """ % formatted_general_info
await self.send_typing(channel)
await self.safe_send_message(channel, """Weather Lookup\n\nEnter the name of the city that you want
to look at the weather details of.""", expire_in=30)
while True:
global city_input
global str_city_input
city_input = await self.wait_for_message(20, author=author, channel=channel)
if not city_input:
return Response("There was no response from "+ str(author) +".",
elif city_input.content.startswith(self.config.command_prefix) or \
str_city_input = city_input.content.strip()
await self.safe_send_message(channel, connectapi())
if 'name' in data:
await self.send_typing(channel)
await self.safe_send_message(channel,"\n%r in %r:\n\nGeneral Info:" % (city_name, country_name))
await self.safe_send_message(channel, formatlines())
await self.safe_send_message(channel, "Something went wrong, would you like to try again?")
except Exception as e:
raise exceptions.CommandError(e, expire_in=20)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment