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
import discord
import os
from discord.ext import commands
from discord.utils import find
from datetime import date, datetime
from discord.ext import tasks
client = discord.Client()
prefix = "!"
#---- Hot news imports & Variables ---------------------------------------------------------------------------------
import site
site.getsitepackages()
import requests
from bs4 import BeautifulSoup
URL = "https://www.bbc.com/news"
page = requests.get(URL)
soup = BeautifulSoup(page.content, "html.parser")
results = soup.find(id="site-container")
HotNews = results.find_all("div", id="latest-stories-tab-container")
links = results.find_all("a")
#--------------------------------------------------------------------------------------------------------------------
#---- Weather -------------------------------------------------------------------------------------------------------
import re
import json
from urllib.request import urlopen
location = ""
#---- ----- -------------------------------------------------------------------------------------------------------
def check(m): #chcek function for next message if it is the same as the user who called the function
return m.author == ctx.author and m.channel == ctx.channel
# - Not finished loop to remind about options
#@tasks.loop(seconds=10)#1 day
#async def mytask():
#mytask.start()
#mytask.channel.send("test")
@client.event
async def on_guild_join(guild):
general = find(lambda x: x.name == 'general', guild.text_channels)
if general and general.permissions_for(guild.me).send_messages:
await general.send('Hello {}!'.format(guild.name)+"\nuse Help for more options and prefix '!'")
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
global location
langauge = 0
hnpf = (prefix + "H")
if message.author == client.user:
return
if message.content.startswith(prefix+'Settings'):
await message.channel.send("‎\n Hello in Eggy's setting\n"+prefix+"Language - For Language settings\n"+prefix+"Help - For help settings\n"+prefix+"Location - To setup location")
if message.content.startswith('Help'):
await message.channel.send('‎\n--------------Eggys--------------\n--------------Help Menu---------------\n**!Settings** - For Bot Preference settings \n**!Weather** or **!W** - For Weather \n**!Hotnews** or **!H** - For Hotnews \n**!Technews** or **!T** - For Technews \n**!Sports** or **!S** - For Sports \n**!Facts** or **!F** - for Random Facts')
if message.content.startswith(prefix + "Location"):
await message.channel.send("Hello your set location at the moment is "+location+"please input your new location")
translateVar = await client.wait_for("message")
location = translateVar.content.lower()
await message.channel.send("New Location is now"+location)
if message.content.startswith(prefix +'Language'):
await message.channel.send("‎\n----------------\n1.English:\n""2.Deutsch :\n""3.Polish:\n----------------")
LanguageChoice = await client.wait_for("message")
if LanguageChoice.content.lower() == "1":
await message.channel.send("English has been chosen")
langauge = 1
return (langauge)
elif LanguageChoice.content.lower() == "2":
await message.channel.send("Deutsch has been chosen")
langauge = 2
return (langauge)
elif LanguageChoice.content.lower() == "3":
await message.channel.send("Polish has been chosen\n Polski Zostal Wybrany")
langauge = 3
return(langauge)
await message.channel.send("test")
if message.content.startswith(prefix +'Weather' or prefix + "W"):
await message.channel.send("‎\n-----------------------------\nWelcome to Eggy's Weather News Today Is :" + datetime.today().strftime('%d-%m-%Y %H:%M:%S'+ "\n-----Menu----\n1.Weather By Set Location \n2.Input location \n-----------------------------"))
FirstChoice = await client.wait_for("message")
if FirstChoice.content.lower() == "1":
if location == "":
await message.channel.send("‎\n-----------------------------\nPlease input location as no location is set\n Example 'Birmingham, UK' \nadd country code incase there is another city\n-----------------------------")
translateVar = await client.wait_for("message")
location = translateVar.content.lower()
city_1 = location
print(city_1)
api_address = "https://api.openweathermap.org/data/2.5/weather?appid=499bb12a435d4b2ee90d62df4229d707&q=" # api to know whether based on location the city of the user is added to the api is input to retrieve whether info
full_link = api_address + city_1
json_data = requests.get(full_link).json()
temp_k = json_data["main"]["temp"]
situation_c = json_data["weather"][0]['main'] # choosing what type of whether i want by accesing it from the api
float(temp_k)
temp_c1 = round(temp_k - 273, 1)
temp_c2 = str(round(temp_k - 273, 1)) + "C"
if temp_c1 < 0:
temp_c = temp_c2 + " \nits freezing out there Wear a coat! "
elif temp_c1 <= 15: # statments outputted based on temp
temp_c = temp_c2 + " \nits cold out there Wear a jacket! "
elif temp_c1 <= 25:
temp_c = temp_c2 + " \nits moderate today a shirt would be fine! "
else:
temp_c = temp_c2 + " \nits hot outside please wear a t-shirt! "
humidity = str(json_data["main"]["humidity"])
await message.channel.send("‎\n-----------------------------\nthe situation is " + situation_c + " today in " + city_1 + "\nwith a humidity of " + humidity + " and a temperature of " + temp_c +"\n-----------------------------") # final statment returned to the user
elif FirstChoice.content.lower() == "2":
await message.channel.send("‎\n-----------------------------\nPlease input your city to find latest whether conditions:\n-----------------------------")
translateVar = await client.wait_for("message")
user_location = translateVar.content.lower()
print(user_location)
api_address = "https://api.openweathermap.org/data/2.5/weather?appid=cdbc612d816811de2f71839e092ee261&q=" # same thing is done here is above but instead of accessing user city by ip address user inputs the city manually
full_link = api_address + user_location
json_data = requests.get(full_link).json()
code_1 = json_data["cod"]
if code_1 == 200:
temp_k = json_data["main"]["temp"]
situation_c = json_data["weather"][0]['main']
float(temp_k)
temp_c1 = round(temp_k - 273, 1)
temp_c2 = str(round(temp_k - 273, 1)) + "C"
if temp_c1 < 0:
temp_c = temp_c2 + " \nits freezing out there Wear a coat! "
elif temp_c1 <= 15:
temp_c = temp_c2 + " \nits cold out there Wear a jacket! "
elif temp_c1 <= 25:
temp_c = temp_c2 + " \nits moderate today a shirt would be fine! "
else:
temp_c = temp_c2 + " \nits hot outside please wear a t-shirt! "
humidity = str(json_data["main"]["humidity"])
code_2 = str(json_data["cod"])
await message.channel.send("‎\n-----------------------------\nthe situation is " + situation_c + " today in " + user_location + " with a humidity of " + humidity + " and a temperature of " + temp_c+"\n-----------------------------")
else:
return()
if message.content.startswith(prefix + 'Technews' or prefix + "T"):
await message.channel.send("Sorry this hasen't been implemented yet by the author")
if message.content.startswith(prefix + 'Facts' or prefix + "F"):
await message.channel.send("Sorry this hasen't been implemented yet by the author")
if message.content.startswith(prefix +'Hotnews' or hnpf):
await message.channel.send("‎\n-----------------------------\nWelcome to Eggy's Hot News Today Is :" + datetime.today().strftime('%d-%m-%Y %H:%M:%S' + "\n-----Menu----\n1.Eggy's Hottest News \n2.Google Latest News \n3.to Exit\n-----------------------------"))
FirstChoice = await client.wait_for("message")
if FirstChoice.content.lower() == "1":
LinkUrls = [] # empty list made for links
for link in links: # loop to get all links from links variable which holds all "a" tags via html
link_url = link["href"] # link_url has the value
FullLink = ("bbc.com" + link_url) # make the "full link to the website because links in html are only extensions missing bbc.com
LinkUrls.append(FullLink) # add "fulllink" to to the LinkUrls list
for Hotstory in HotNews: # loop to use for Hotstory & descirption
hotstory2 = Hotstory.find("h3",class_="gs-c-promo-heading__title gel-paragon-bold nw-o-link-split__text")
# hotstory2 is the hot story h3 and class if found in html
hotstory3 = Hotstory.find_all("h3",class_="gs-c-promo-heading__title gel-pica-bold nw-o-link-split__text")
# hotstory3 is a list of all h3 headers with the class as above this is because the stories had all the
# same classes and all h3 so to fix this and get the stories i made a list of all of them which i later simply
# used in the loop to add the 8 stories i need to the "stories" list after removcing all the html code from
# to leave just text
descriptionDone = Hotstory.find("p",class_="gs-c-promo-summary gel-long-primer gs-u-mt nw-c-promo-summary")
# the same as for hotstory2/3 the but with the "p" insted of the h3 header in html
descriptionlist = Hotstory.find_all("p",class_="gs-c-promo-summary gel-long-primer gs-u-mt nw-c-promo-summary")
# the same as for hotstory2/3 the but with the "p" insted of the h3 header in html
Stories = [] # list of Stories which will be added once only text remaning
StoryDescriptions = [] # list of descriptions which will be added once only text reamining
c = 0 # counter for the next loop to
for x in range(0, 9): # loop for 8 stories and descriptions
hottest = "".join(str(hotstory3[c:c + 1])) # takes out certain entry in list hootstory3 and changes it to str
# so that we can edit it more easily, using c:c+1 to make sure we only get the first inputs in the list because
# we need the closest ones
hottest = hottest.replace('<h3 class="gs-c-promo-heading__title gel-pica-bold nw-o-link-split__text">', '')
hottest = hottest.replace('</h3>', '')
hottest = hottest.translate({ord(']'): None})
hottest = hottest.replace('[', '')
# all lines replace parts of the str which are not need to keep just text
Description = "".join(str(descriptionlist[c:c + 1]))
Description = Description.replace('< p class="gs-c-promo-summary gel-long-primer gs-u-mt nw-c-promo-summary">', '')
Description = Description.replace('</p>', '')
Description = Description.translate({ord(']'): None})
# all lines replace parts of the str which are not need to keep just text
Stories.append(hottest) # add each loop of hottest to the stories list ready for print
StoryDescriptions.append(Description) # add each loop of Description to the StoryDescriptions list ready for print
c = c + 1 # add c+1 so that the next loop has a different value for line 40&48
# """ Story 1 """
# lines 47 to 50 are example of code which is used now in the loop from line 32 to 44 which prior to this was
# all duplicate like below however due to an error with the loop i couldn't fix it however i managed to fix it
# and make a single loop and delte 100+ lines
# description1 = "".join(str(descriptionlist[2]))
# description1 = description1.replace('<p class="gs-c-promo-summary gel-long-primer gs-u-mt nw-c-promo-summary">', '')
# description1 = description1.replace('</p>', '')
# description1 = description1.translate({ord(']'): None})
await message.channel.send("‎\n-----------------------------Todays Biggest News-----------------------------"+"\nWelcome to today's hottest news from BBC \nToday is " + datetime.today().strftime( '%d-%m-%Y %H:%M:%S')+"\n-----------------------------Todays Biggest News-----------------------------\nStroy 1 " + hotstory2.text + "\nStroy 2 " + str(Stories[0]) + "\nStroy 3 " + str(Stories[1]) + "\nStroy 4 " + str(Stories[2]) + "\nStroy 5 " + str(Stories[3]) + "\nStroy 6 " + str(Stories[4]) + "\nStroy 7 " + str(Stories[5]) + "\nStroy 8 " + str(Stories[6]).translate({ord('['): None}) + "\n----------------------------------------------------------\nFor More information Type the story number\n otherwise don't do anything ")
Choice = await client.wait_for("message")
if Choice.content.lower() == "1":
#os.system('cls')
await message.channel.send('‎\n----------------------------------------------------------\n"' + descriptionDone.text + '"\nfor more infromation head too\n----------------------------------------------------------')
await message.channel.send(str(LinkUrls[3:4]))
elif Choice.content.lower() == "2":
await message.channel.send('‎\n----------------------------------------------------------\n"' + str(StoryDescriptions[2]) + '"\nfor more infromation head too\n----------------------------------------------------------')
await message.channel.send(str(LinkUrls[10]))
elif Choice.content.lower() == "3":
await message.channel.send('‎\n----------------------------------------------------------\n"' + str(StoryDescriptions[3]) + '"\nfor more infromation head too\n----------------------------------------------------------')
await message.channel.send(str(LinkUrls[12]))
elif Choice.content.lower() == "4":
await message.channel.send('‎\n----------------------------------------------------------\n"' + str(StoryDescriptions[4]) + '"\nfor more infromation head too\n----------------------------------------------------------')
await message.channel.send(str(LinkUrls[14]))
elif Choice.content.lower() == "5":
await message.channel.send('‎\n----------------------------------------------------------\n"' + str(StoryDescriptions[5]) + '"\nfor more infromation head too\n----------------------------------------------------------')
await message.channel.send(str(LinkUrls[16]))
elif Choice.content.lower() == "6":
await message.channel.send('‎\n----------------------------------------------------------\n"' + str(StoryDescriptions[6]) + '"\nfor more infromation head too\n----------------------------------------------------------')
await message.channel.send(str(LinkUrls[19]))
elif Choice.content.lower() == "7":
await message.channel.send('‎\n----------------------------------------------------------\n"' + str(StoryDescriptions[7]) + '"\nfor more infromation head too\n----------------------------------------------------------')
await message.channel.send(str(LinkUrls[21]))
elif Choice.content.lower() == "8":
await message.channel.send('‎\n----------------------------------------------------------\n"' + str(StoryDescriptions[8]) + '"\nfor more infromation head too\n----------------------------------------------------------')
await message.channel.send(str(LinkUrls[24]))
elif Choice.content.lower() == "exit" or "Exit":
return ()
else:
print("\n I dont undeserstand please try again ")
continue
elif FirstChoice.content.lower() == "2":
os.system("cls")
await message.channel.send("For Another Story type !H or !Hotstory")#used for myself to check if the function ended and returned to start
<<<<<<< HEAD:DiscordTest.py
client.run('OTAzNjI0NDczODU1NTU3NjYy.YXvr3w.LWntlaA2VYRSN8IOS3IYpFFuWFw')# token used to connect and create instance of bot
=======
client.run('OTAzNjI0NDczODU1NTU3NjYy.YXvr3w.LWntlaA2VYRSN8IOS3IYpFFuWFw')
>>>>>>> b206b1b7bb2b04bfbfbe3262a2fe6226f79f7afc:Discord.py