Advertisement
DogPl

bot_fb

Mar 24th, 2020
675
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 14.59 KB | None | 0 0
  1. import fbchat
  2. import random as rd
  3. import requests
  4. import feedparser
  5. from bs4 import BeautifulSoup
  6. import json
  7. import asyncio
  8.  
  9.  
  10. class Bot(fbchat.Client):
  11.  
  12.     async def on_inbox(self, unseen=None, unread=None, recent_unread=None, msg=None):
  13.         thread_ids = []
  14.         thread_ids += [thread.uid for thread in await self.fetch_thread_list(thread_location=fbchat.ThreadLocation.PENDING, limit=20)]
  15.         thread_ids += [thread.uid for thread in await self.fetch_thread_list(thread_location=fbchat.ThreadLocation.OTHER, limit=20)]
  16.         await self.move_threads(fbchat.ThreadLocation.INBOX, thread_ids)
  17.  
  18.     async def on_people_added(self,mid=None,added_ids=None,author_id=None,thread_id=None,at=None,msg=None,):
  19.         if thread_id in mutelist:
  20.             pass
  21.         else:
  22.             await self.send(fbchat.Message("Witaj w grupie! Jeśli chcesz zobaczyć moje funckje napisz help"), thread_id=thread_id, thread_type=fbchat.ThreadType.GROUP)
  23.  
  24.     async def on_person_removed(self,mid=None,removed_id=None,author_id=None,thread_id=None,at=None,msg=None,):
  25.         if thread_id in mutelist:
  26.             pass
  27.         else:
  28.             await self.send(fbchat.Message("ktos upuscil grupe"), thread_id=thread_id, thread_type=fbchat.ThreadType.GROUP)
  29.  
  30.     async def on_message(self,mid=None,author_id=None,message_object=None,thread_id=None,thread_type=fbchat.ThreadType.USER,at=None,metadata=None,msg=None,):
  31.         if author_id != self.uid:
  32.             message_text = str(message_object.text).lower()
  33.  
  34.  
  35.             if message_object.text == "!mem":
  36.                 drawing_meme = str(rd.randint(1, 199))
  37.                 await self.send_local_files(["mem"+drawing_meme+".png"], thread_id=thread_id, thread_type=thread_type)
  38.  
  39.             elif message_object.text == "!koronawirus":
  40.                 data = requests.get("https://coronavirus-19-api.herokuapp.com/all").json()
  41.                 message = f"Total confirmed: {data['cases']}\nTotal deaths: {data['deaths']}\nTotal recovered: {data['recovered']}\nExisting: {data['cases'] - data['deaths'] - data['recovered']}"
  42.                 await self.send(fbchat.Message(text=message), thread_id=thread_id, thread_type=thread_type)
  43.  
  44.             elif message_object.text == "!koronawiruspl":
  45.                 data = requests.get("https://coronavirus-19-api.herokuapp.com/countries").json()
  46.                 for i in data:
  47.                     if i["country"] == "Poland":
  48.                         message = f"Total confirmed: {i['cases']}\nToday confirmed: {i['todayCases']}\nTotal deaths: {i['deaths']}\nTotal recovered: {i['recovered']}\nExisting: {i['active']}"
  49.                         await self.send(fbchat.Message(text=message), thread_id=thread_id, thread_type=thread_type)
  50.                         pass
  51.  
  52.             elif message_object.text == "!luckymember":
  53.                 if thread_type == fbchat.ThreadType.GROUP:
  54.                     group_members = list((await self.fetch_thread_info(thread_id))[thread_id].participants)
  55.                     lucky_member = rd.randint(0,len(group_members)-1)
  56.                     lucky_member = group_members[lucky_member]
  57.                     await self.send(fbchat.Message(text="Zwycięzca", mentions=[fbchat.Mention(lucky_member)]),thread_id=thread_id, thread_type=thread_type)
  58.                 else:
  59.                     await self.send(fbchat.Message("To komenda dla grup"),thread_id=thread_id,thread_type=thread_type)
  60.  
  61.             if message_object.text == "!para":
  62.                 if thread_type == fbchat.ThreadType.GROUP:
  63.                     group_members = list((await self.fetch_thread_info(thread_id))[thread_id].participants)
  64.                     first_person = rd.randint(0,len(group_members)-1)
  65.                     first_person = group_members[first_person]
  66.                     secend_person = rd.randint(0, len(group_members)-1)
  67.                     secend_person = group_members[secend_person]
  68.                     await self.send(fbchat.Message(text="Mąz", mentions=[fbchat.Mention(first_person)]),thread_id=thread_id, thread_type=thread_type)
  69.                     await self.send(fbchat.Message(text="Żona", mentions=[fbchat.Mention(secend_person)]),thread_id=thread_id, thread_type=thread_type)
  70.                 else:
  71.                     await self.send(fbchat.Message("To komenda dla grup"),thread_id=thread_id,thread_type=thread_type)
  72.  
  73.             elif message_object.text == "!disco":
  74.                 for i in range(0,20):
  75.                     change_color = rd.choice([fbchat.ThreadColor.BRIGHT_TURQUOISE, fbchat.ThreadColor.BILOBA_FLOWER, fbchat.ThreadColor.BRILLIANT_ROSE, fbchat.ThreadColor.CAMEO, fbchat.ThreadColor.DARK_TANGERINE, fbchat.ThreadColor.DEEP_SKY_BLUE, fbchat.ThreadColor.FERN, fbchat.ThreadColor.FREE_SPEECH_GREEN, fbchat.ThreadColor.GOLDEN_POPPY, fbchat.ThreadColor.LIGHT_CORAL, fbchat.ThreadColor.MALACHITE, fbchat.ThreadColor.MEDIUM_SLATE_BLUE, fbchat.ThreadColor.MESSENGER_BLUE, fbchat.ThreadColor.PICTON_BLUE, fbchat.ThreadColor.PUMPKIN, fbchat.ThreadColor.RADICAL_RED, fbchat.ThreadColor.RUBY, fbchat.ThreadColor.SHOCKING, fbchat.ThreadColor.TICKLE_ME_PINK, fbchat.ThreadColor.VIKING])
  76.                     await self.change_thread_color(color=change_color ,thread_id=thread_id)
  77.  
  78.             elif message_object.text == "!utrudnieniawawa":
  79.                 feed = feedparser.parse('https://www.wtp.waw.pl/feed/?post_type=impediment')
  80.                 wiadomosc = ""
  81.                 for entry in feed['entries']:
  82.                     wiadomosc += str(entry.title).upper() + "\n"
  83.                     wiadomosc += entry.published[:-9] + "\n"
  84.                     wiadomosc += entry.summary + "\n"
  85.                     wiadomosc += "\n"
  86.                 if wiadomosc == "":
  87.                     await self.send(fbchat.Message("Brak utrudnień w Warszawie :)"), thread_id=thread_id, thread_type=thread_type)
  88.                 else:
  89.                     await self.send(fbchat.Message(wiadomosc), thread_id=thread_id, thread_type=thread_type)
  90.  
  91.             elif message_object.text == "!utrudnieniawroclaw":
  92.                 data = requests.get("https://www.facebook.com/mpkwroc/")
  93.                 soup = BeautifulSoup(data.text, "html.parser")
  94.                 sformatowane_dane = ""
  95.                 for i in soup.find_all("p"):
  96.                     sformatowane_dane += str(i) + "\n"
  97.                 sformatowane_dane = BeautifulSoup(sformatowane_dane, "html.parser").text
  98.                 await self.send(fbchat.Message(sformatowane_dane), thread_id=thread_id, thread_type=thread_type)
  99.  
  100.             elif message_object.text == "!utrudnienialodz":
  101.                 data = requests.get("http://www.mpk.lodz.pl/rozklady/utrudnienia.jsp")
  102.                 soup = BeautifulSoup(data.text, "html.parser")
  103.                 sformatowane_dane = ""
  104.                 for i in soup.find_all("p"):
  105.                     if "MPK na facebook".lower() in str(i).lower():
  106.                         sformatowane_dane += "\n"
  107.                     elif "Zamknij" in str(i):
  108.                         break
  109.                     else:
  110.                         sformatowane_dane += str(i) + "\n"
  111.                 sformatowane_dane = BeautifulSoup(sformatowane_dane, "html.parser").text
  112.                 await self.send(fbchat.Message(text="Właścicielami danych jest http://www.mpk.lodz.pl/rozklady/utrudnienia.jsp\n{0} ".format(sformatowane_dane)), thread_id=thread_id, thread_type=thread_type)
  113.  
  114.             elif "!pogoda" in message_object.text:
  115.                 try:
  116.                     api_address = 'http://api.openweathermap.org/data/2.5/weather?appid=myid&q='
  117.                     city = message_object.text[8:]
  118.                     url = api_address + city
  119.                     json_data = requests.get(url).json()
  120.                     temperature = json_data["main"]["temp"]
  121.                     temperature -= 273
  122.                     feel_temperature = json_data["main"]["feels_like"]
  123.                     feel_temperature -= 273
  124.                     weather = json_data["weather"][0]["description"]
  125.                     preassure = json_data["main"]["pressure"]
  126.                     humidity = json_data["main"]["humidity"]
  127.                     wind_speed = json_data["wind"]["speed"]
  128.                     full_weather = """Pogoda w {0}
  129. Temperatura: {1} C
  130. Odczuwalna: {2} C
  131. Atmosfera: {3}
  132. Ciśnienie: {4} hPa
  133. Wilgotność: {5} %
  134. Prędkość wiatru: {6} m/s""".format(str(city).title(),int(temperature),int(feel_temperature),weather,preassure,humidity,wind_speed)
  135.                     await self.send(fbchat.Message(full_weather),thread_id=thread_id, thread_type=thread_type)
  136.                 except:
  137.                     await self.send(fbchat.Message("Nie znalezione takiej miejscowości, lub linux nie umie odczytać polskiego znaku. Spróbuj wpisać nazwe miejscowości bez polskich znakow"),thread_id=thread_id, thread_type=thread_type)
  138.  
  139.             elif message_object.text == "!ruletka":
  140.                 if thread_type == fbchat.ThreadType.GROUP:
  141.                     group = (await self.fetch_group_info(thread_id))[thread_id]
  142.                     group_admins = group.admins
  143.                     group_members = list((await self.fetch_thread_info(thread_id))[thread_id].participants)
  144.                     member_to_kick = rd.choice(group_members)
  145.                     if self.uid not in group_admins:
  146.                         await self.send(fbchat.Message("Nie mam admina (jeśli chcesz by działała ta komenda, musisz dać mi admina na tej grupie)"), thread_id=thread_id, thread_type=thread_type)
  147.                     elif author_id not in group_admins:
  148.                         await self.send(fbchat.Message("To komenda tylko dla adminów (tylko admini danej grupy mogą używac tej komendy)"),thread_id=thread_id, thread_type=thread_type)
  149.                     else:
  150.                         if member_to_kick in group_admins:
  151.                             await self.send(fbchat.Message("Wylosowalo admina. Nie moge go usunąć"),thread_id=thread_id ,thread_type=thread_type)
  152.                         else:
  153.                             await self.remove_user_from_group(member_to_kick,thread_id=thread_id)
  154.                 else:
  155.                     await self.send(fbchat.Message("To komenda dla grup"), thread_id=thread_id, thread_type=thread_type)
  156.  
  157.             elif "!nick" in message_object.text:
  158.                 try:
  159.                     await self.change_nickname(message_object.text[5:], user_id=author_id, thread_id=thread_id, thread_type=thread_type)
  160.                 except:
  161.                     await self.send(fbchat.Message("Linux nie moze odczytać polskiej litery, albo wpisałes za długi nick"), thread_id=thread_id, thread_type=thread_type)
  162.  
  163.             elif message_object.text == "!mute":
  164.                 x = ""
  165.                 if thread_type != fbchat.ThreadType.GROUP:
  166.                     await self.send(fbchat.Message("To komenda tylko dla grup"), thread_id=thread_id, thread_type=thread_type)
  167.                     x = "stop"
  168.                 if x == "stop":
  169.                     pass
  170.                 else:
  171.                     group = (await self.fetch_group_info(thread_id))[thread_id]
  172.                     group_admins = group.admins
  173.                     if author_id not in group_admins:
  174.                         await self.send(fbchat.Message("Tylko administartor grupy może używać tej funkcji"), thread_id=thread_id, thread_type=thread_type)
  175.                     else:
  176.                         if thread_id in mutelist:
  177.                             await self.send(fbchat.Message("Jestem zmutowany. Aby mnie odmutować napisz !unmute"), thread_id=thread_id, thread_type=thread_type)
  178.                         else:
  179.                             await self.send(fbchat.Message("Zostalem zmutowany. Aby mnie odmutowac napisz !unmute"), thread_id=thread_id, thread_type=thread_type)
  180.                             mutelist.append(thread_id)
  181.                             with open("mutelist.json", "w") as write_file:
  182.                                 json.dump(mutelist, write_file)
  183.  
  184.             elif message_object.text == "!unmute":
  185.                 x = ""
  186.                 if thread_type != fbchat.ThreadType.GROUP:
  187.                     await self.send(fbchat.Message("To komenda tylko dla grup"), thread_id=thread_id, thread_type=thread_type)
  188.                     x = "stop"
  189.                 if x == "stop":
  190.                     pass
  191.                 else:
  192.                     group = (await self.fetch_group_info(thread_id))[thread_id]
  193.                     group_admins = group.admins
  194.                     if author_id not in group_admins:
  195.                         await self.send(fbchat.Message("Tylko administrator grupy może używać tej funkcji"), thread_id=thread_id, thread_type=thread_type)
  196.                     else:
  197.                         if thread_id in mutelist:
  198.                             await self.send(fbchat.Message("Nie jestem już zmutowany :)"), thread_id=thread_id, thread_type=thread_type)
  199.                             mutelist.remove(str(thread_id))
  200.                             with open("mutelist.json", "w") as write_file:
  201.                                 json.dump(mutelist, write_file)
  202.                         else:
  203.                             await self.send(fbchat.Message("Nie jestem zmutowany"), thread_id=thread_id, thread_type=thread_type)
  204.  
  205.             elif "!losuj" in message_object.text:
  206.                 try:
  207.                     numbers = str(message_object.text).split()
  208.                     drawed_number = rd.randint(int(numbers[1]), int(numbers[2]))
  209.                     await self.send(fbchat.Message("Wylosowano: " + str(drawed_number)), thread_id=thread_id, thread_type=thread_type)
  210.                 except:
  211.                     await self.send(fbchat.Message("Losuje tylko pełne liczby"))
  212.  
  213.             elif message_object.text == "!everyone":
  214.                 if thread_id in mutelist:
  215.                     await self.send(fbchat.Message("Zły admin wyłączył te funkcję mutująć mnie :("),thread_id=thread_id, thread_type=thread_type)
  216.                 else:
  217.                     group_members = list((await self.fetch_thread_info(thread_id))[thread_id].participants)
  218.                     mentions = []
  219.                     for member in range(len(group_members)):
  220.                         mentions.append(fbchat.Mention(group_members[member], offset=0))
  221.                     await self.send(fbchat.Message("ELUWA ALL", mentions=mentions),thread_id=thread_id, thread_type=thread_type)
  222.  
  223.  
  224.  
  225.  
  226.  
  227. mail = ""
  228. password = ""
  229.  
  230. loop = asyncio.get_event_loop()
  231.  
  232. async def start():
  233.     bot = Bot(loop=loop)
  234.     print("loggin in...")
  235.     await bot.start(email=mail, password=password)
  236.     print("listening...")
  237.     await bot._listen_mqtt()
  238.     print("listening stopped")
  239.  
  240. loop.create_task(start())
  241. loop.run_forever()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement