Advertisement
Guest User

Untitled

a guest
Jan 20th, 2018
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 17.21 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # coding: utf8
  3.  
  4. from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, RegexHandler,
  5.                           ConversationHandler, StringCommandHandler, Dispatcher)
  6.  
  7. from telegram.ext.dispatcher import run_async
  8. from telegram import MessageEntity, ChatAction
  9. from random import randint
  10. import logging
  11. import csv
  12. import re
  13. import sys
  14. import time
  15. import traceback
  16.  
  17. # locale.setlocale(locale.LC_ALL,"de_DE")
  18.  
  19. reload(sys)  
  20. sys.setdefaultencoding('utf8')
  21.  
  22. # Enable logging
  23. logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
  24.                     level=logging.INFO)
  25.  
  26. logger = logging.getLogger(__name__)
  27.  
  28.  
  29. def start(bot, update):
  30.  
  31.     update.message.reply_text(
  32.         'Hallo! Hier ist Butler Murphy und ich kann dir helfen, wenn du mir ein Befehl schickst.\n'
  33.         'Frage mich nach der Liste mit #liste und du bekommst alle möglichen Befehle aufgelistet.\n')
  34.  
  35.  
  36.  
  37.  
  38. @run_async
  39. def doSleepDel(bot, update, send, sleeptime, kind):
  40.     # print(bot)
  41.     # print(update)
  42.     # print(send)
  43.     # print(sleeptime)
  44.     # print(kind)
  45.     # print(type(send))
  46.     try:
  47.         # if update.effective_chat.type == 'private':
  48.         #     if kind == 1:
  49.         #         bot.send_message(chat_id=update.message.chat_id, text=send, parse_mode='Markdown', disable_web_page_preview=True)
  50.         #         #update.message.reply_text(send, parse_mode='Markdown', disable_web_page_preview=True)
  51.         #     elif kind == 2:
  52.         #         bot.send_photo(chat_id=update.message.chat_id, photo=open(send, 'rb'))
  53.         #         #update.message.reply_photo(photo=open(send, 'rb'))
  54.  
  55.        
  56.         if kind == 1:
  57.             bot.send_chat_action(chat_id=update.message.chat_id, action=ChatAction.TYPING, timeout=5)
  58.             send = update.message.reply_text(send, timeout=5, parse_mode='Markdown', disable_web_page_preview=True)
  59.         elif kind == 2:
  60.             bot.send_chat_action(chat_id=update.message.chat_id, action=ChatAction.UPLOAD_PHOTO, timeout=10)
  61.             send = update.message.reply_photo(photo=open(send, 'rb'), timeout=10, UPLOAD_PHOTO = 'upload_photo')
  62.  
  63.         if update.effective_chat.type == 'supergroup':
  64.             time.sleep(sleeptime)
  65.             bot.delete_message(chat_id=update.message.chat_id, message_id=send['reply_to_message']['message_id'])
  66.             bot.delete_message(chat_id=update.message.chat_id, message_id=send['message_id'])
  67.     except:
  68.         traceback.print_exc()
  69.         print("Exception")
  70.         doSleepDel(bot, update, send, 20, 1)
  71.  
  72.         # if kind == 1:
  73.         #     send = update.message.reply_text(send, parse_mode='Markdown', disable_web_page_preview=True)
  74.         # elif kind == 2:
  75.         #     send = update.message.reply_photo(photo=open(send, 'rb'))
  76.  
  77.         # if not update.effective_chat.kind == 'private':
  78.         #     time.sleep(sleeptime)
  79.         #     bot.delete_message(chat_id=update.message.chat_id, message_id=send['reply_to_message']['message_id'])
  80.         #     bot.delete_message(chat_id=update.message.chat_id, message_id=send['message_id'])
  81.    
  82. @run_async
  83. def hashtag(bot, update):
  84.     logger.info("Mitglied: %s; Eingabe: %s", update.message.from_user.first_name, update.message.text)
  85.  
  86.     hashtag = update.message.text.lower().split()[0]
  87.  
  88.     if '#' in hashtag: #Muss sein, da sonst im gesamten Text nach Hashtags gesucht wird.
  89.  
  90.         if '#adblue' == hashtag:
  91.             send = "[AdBlue Zapfsäulen](http://goo.gl/4i5opM)"
  92.             doSleepDel(bot, update, send, 10, 1)
  93.  
  94.         elif '#bahn' == hashtag:
  95.             send = ("[Hauptbahnhof](https://iris.noncd.db.de/wbt/js/index.html?typ=an&bhf=BL&zugtyp=&platform=&bhfname=&style=an&via=0&impressum=0&lang=de&SecLang=&zeilen=17&paging=&pagingdauer=&impressum=0);"
  96.                     "[Nur ICE](https://iris.noncd.db.de/wbt/js/index.html?typ=an&bhf=BL&zugtyp=ICE&platform=&bhfname=&style=an&via=0&impressum=0&lang=de&SecLang=&zeilen=17&paging=&pagingdauer=&impressum=0)\n"
  97.                 "[Ostbahnhof](https://iris.noncd.db.de/wbt/js/index.html?typ=an&bhf=BHF&zugtyp=&platform=&bhfname=&style=an&via=0&impressum=0&lang=de&SecLang=&zeilen=17&paging=&pagingdauer=&impressum=0);"
  98.                 "[Nur ICE](https://iris.noncd.db.de/wbt/js/index.html?typ=an&bhf=BHF&zugtyp=ICE&platform=&bhfname=&style=an&via=0&impressum=0&lang=de&SecLang=&zeilen=17&paging=&pagingdauer=&impressum=0)\n"
  99.                 "[Bf Gesundbrunnen](https://iris.noncd.db.de/wbt/js/index.html?typ=an&bhf=BGS&zugtyp=&platform=&bhfname=&style=an&via=0&impressum=0&lang=de&SecLang=&zeilen=17&paging=&pagingdauer=&impressum=0);"
  100.                 "[Nur ICE](https://iris.noncd.db.de/wbt/js/index.html?typ=an&bhf=BGS&zugtyp=ICE&platform=&bhfname=&style=an&via=0&impressum=0&lang=de&SecLang=&zeilen=17&paging=&pagingdauer=&impressum=0)\n"
  101.                 "[Bf Südkreuz](https://iris.noncd.db.de/wbt/js/index.html?typ=an&bhf=BPAF&zugtyp=&platform=&bhfname=&style=an&via=0&impressum=0&lang=de&SecLang=&zeilen=17&paging=&pagingdauer=&impressum=0);"
  102.                 "[Nur ICE](https://iris.noncd.db.de/wbt/js/index.html?typ=an&bhf=BPAF&zugtyp=ICE&platform=&bhfname=&style=an&via=0&impressum=0&lang=de&SecLang=&zeilen=17&paging=&pagingdauer=&impressum=0)\n"
  103.                 "[Bf Spandau](https://iris.noncd.db.de/wbt/js/index.html?typ=an&bhf=BSPD&zugtyp=&platform=&bhfname=&style=an&via=0&impressum=0&lang=de&SecLang=&zeilen=17&paging=&pagingdauer=&impressum=0);"
  104.                 "[Nur ICE](https://iris.noncd.db.de/wbt/js/index.html?typ=an&bhf=BSPD&zugtyp=ICE&platform=&bhfname=&style=an&via=0&impressum=0&lang=de&SecLang=&zeilen=17&paging=&pagingdauer=&impressum=1)\n"
  105.                 "[Bf Zoo](https://iris.noncd.db.de/wbt/js/index.html?typ=an&bhf=BZOO&zugtyp=&platform=&bhfname=&style=an&via=0&impressum=0&lang=de&SecLang=&zeilen=17&paging=&pagingdauer=&impressum=0);"
  106.                 "[Nur ICE](https://iris.noncd.db.de/wbt/js/index.html?typ=an&bhf=BZOO&zugtyp=ICE&platform=&bhfname=&style=an&via=0&impressum=0&lang=de&SecLang=&zeilen=17&paging=&pagingdauer=&impressum=0)")
  107.             doSleepDel(bot, update, send, 60, 1)
  108.  
  109.         elif '#bordell' == hashtag:
  110.             send = "[Karte mit Bordellen](https://goo.gl/hn4vYQ)"
  111.             doSleepDel(bot, update, send, 10, 1)
  112.  
  113.         elif '#cash' == hashtag:
  114.             send = "[Karte mit Geldautomaten](https://finde.cash/)"
  115.             doSleepDel(bot, update, send, 20, 1)
  116.  
  117.         elif '#clubs' == hashtag:
  118.             send = ("*Clublisten:*\n"
  119.                     "[RA Guide](https://www.residentadvisor.net/events)\n"
  120.                     "[Blout!](http://blout.appyo.de/)\n"
  121.                     "[Gästeliste030](https://www.gaesteliste030.de/)\n"
  122.                     "[Virtual Nights](https://www.virtualnights.com/berlin/events)")
  123.             doSleepDel(bot, update, send, 60, 1)  
  124.  
  125.         elif '#dbfahrt' == hashtag:
  126.             try:
  127.                 km = float(update.message.text.lower().split()[1].replace(',','.'))
  128.  
  129.                 euroProKm4 = 0.87
  130.                 euroProKm5 = 1
  131.  
  132.                 erg4 = 2*km*euroProKm4
  133.                 erg5 = 2*km*euroProKm5
  134.  
  135.                 send = ("Die {} km lange Fahrt würde kosten:\n"
  136.                         "*Mit max. 4 Personen:*\n   Netto: {:.2f} €\n   Brutto: {:.2f} €\n"
  137.                         "*Mit über 5 Personen:*\n   Netto: {:.2f} €\n   Brutto: {:.2f} €"
  138.                         .format(mN(km), mN(erg4), mN(erg4*1.19), mN(erg5), mN(erg5*1.19)))
  139.                 doSleepDel(bot, update, send, 60, 1)
  140.  
  141.             except:
  142.                 traceback.print_exc()
  143.                 send = "Entweder fehlt die Anzahl der Kilometer oder die Eingabe ist ungültig."
  144.                 doSleepDel(bot, update, send, 10, 1)
  145.  
  146.         elif '#fashion' == hashtag:
  147.             send = "[Fashion Week Kalender](https://t.co/RGxOflosJf?ssr=true)"
  148.             doSleepDel(bot, update, send, 10, 1)
  149.  
  150.         elif '#funk' == hashtag:
  151.             send = "[Funk Taxi Berlin (WBT)](https://m.taxi4me.net/mobile/index2.html?z=2620)"
  152.             doSleepDel(bot, update, send, 10, 1)
  153.  
  154.         elif '#hbf' == hashtag:
  155.             send = "#hbf wurde durch #bahn ersetzt."
  156.             doSleepDel(bot, update, send, 10, 1)
  157.  
  158.         elif '#hp' == hashtag:
  159.             send = "[Karte mit Taxi-Halteplätzen](https://goo.gl/VXngKZ)"
  160.             doSleepDel(bot, update, send, 10, 1)
  161.  
  162.         elif '#kotze' == hashtag:
  163.             send = 'kotze.jpg'
  164.             doSleepDel(bot, update, send, 60, 2)
  165.              
  166.         elif '#links' == hashtag:
  167.             send = ("*Taxi Gruppe Berlin:*\n"
  168.                     "_(Nur arbeitsbezogene Meldungen und Fragen.)_"
  169.                     "\t [https://t.me/joinchat/Ftnlv08gvnQmzDEVtfHcsA](https://t.me/joinchat/Ftnlv08gvnQmzDEVtfHcsA)\n\n"
  170.                     "*TGB Verkehr:*\n"
  171.                     "_(Nur Verkehrsbezogene Meldungen und Fragen.)_\t"
  172.                     "[https://t.me/joinchat/Ftnlv0pyBjqQlz7Fk_Ic-A](https://t.me/joinchat/Ftnlv0pyBjqQlz7Fk_Ic-A)\n\n"
  173.                     "*TGB Lobby:*\n"
  174.                     "_(Sonstige Fragen, SMALLtalk, Dialog mit Taxifahrern.)_\t"
  175.                     "[https://t.me/joinchat/Ftnlv02oVBIF7NC6Y_CWVw](https://t.me/joinchat/Ftnlv02oVBIF7NC6Y_CWVw)")
  176.             doSleepDel(bot, update, send, 60, 1)
  177.  
  178.         elif '#liste' == hashtag:
  179.             send = ("*Liste aller Hashtags:*\n\n"
  180.                 "#adblue: Tankstellenkarte mit AdBlue Zapfsäulen.\n"
  181.                 "#bahn: Ankunftszeiten an Bahnhöfen.\n"
  182.                 "#bordell: Karte mit Bordellen.\n"
  183.                 "#cash: Karte mit Bankautomaten.\n"
  184.                 "#clubs: Links von 4 Clubseiten.\n"
  185.                 "#dbfahrt: Fahrtkostenrechner für DB Fahrten."
  186.                 "#fashion: Fashion Week Kalender\n"
  187.                 "#funk: Taxi Bestellung über Funk Taxi Berlin (WBT)\n"
  188.                 "#hp: Karte mit Taxi-Halteplätzen.\n"
  189.                 "#kotze: Zeigt eine Liste mit Gebühren für ein vollgekotztes Taxi.\n"
  190.                 "#links: Gruppenlinks\n"
  191.                 "#liste: Diese Hashtagliste.\n"
  192.                 "#messe: Aktuelle Messen.\n"
  193.                 "#messeplan: Lageplan der Messe.\n"
  194.                 "#mytaxi: Link der MyTaxi Fahrerapp.\n"
  195.                 "#persius: Link der Taxi Berlin Fahrerapp.\n"
  196.                 "#preis: Fahrtkostenrechner.\n"
  197.                 "#qp: QPark TXL Öffnungszeiten und Tel.-Nr.\n"
  198.                 "#qr: QR-Code der Gruppe, zum schnellen teilen des Links.\n"
  199.                 "#sektor: Zeigt den Sektornamen zur Sektornummer. Eingabe: #sektor \[Nr.]\n"
  200.                 "#sp: 24/7 Spätkäufe.\n"
  201.                 "#taxi: Taxi Bestellung über Taxi Berlin.\n"
  202.                 "#tr: Fahrtkostenechner per Google Maps.\n"
  203.                 "#txl: TXL Ankünfte.\n"
  204.                 "#wasch: 24/7 Waschanlagen.\n"
  205.                 "#wc: Karte mit Toiletten.\n"
  206.                 "#zob: ZOB Ankünfte.")
  207.             doSleepDel(bot, update, send, 60, 1)  
  208.  
  209.         elif '#messe' == hashtag:
  210.             send = "[Aktuelle Messen](https://rbbtext.mobi/597)"
  211.             doSleepDel(bot, update, send, 40, 1)
  212.  
  213.         elif '#messeplan' == hashtag:
  214.             send = 'messeplan.jpg'
  215.             doSleepDel(bot, update, send, 40, 2)
  216.  
  217.         elif '#mytaxi' == hashtag:
  218.             send = "[MyTaxi Fahrerapp](https://d.mytaxi.com/)\n 24/7 Rufnummer: +49 171 7631803"
  219.             doSleepDel(bot, update, send, 10, 1)
  220.  
  221.         elif '#persius' == hashtag:
  222.             send = "[Taxi Berlin Fahrerapp (Android)](http://www.taxi.eu/fahrerapp)"
  223.             doSleepDel(bot, update, send, 10, 1)
  224.  
  225.         elif '#preis' == hashtag:  
  226.             try:
  227.                 km = float(update.message.text.lower().split()[1].replace(',','.'))
  228.  
  229.                 if 0 < km < 50:
  230.                     if km <= 7:
  231.                         send = "Die Fahrt würde ungefähr {}€ kosten.".format(format_number_0b(3.90+(2*km)))
  232.                     elif km >7:
  233.                         send = "Die Fahrt würde ungefähr {}€ kosten.".format(format_number_0b(7.40+(km * 1.5)))
  234.                        
  235.                 elif km >=50:
  236.                     send = ("Die Fahrt würde ungefähr {}€ kosten.\n"
  237.                             "Es scheint sich um eine Umland-\Fernfahrt zu handeln. In diesem Falle solltest du {}€ verlangen."
  238.                             .format(format_number_0b(7.40+(km * 1.5)), format_number_0b(3.90+(2*km))))
  239.                
  240.                 else:
  241.                     send = "Gib eine Zahl größer als 0 ein."
  242.  
  243.                 doSleepDel(bot, update, send, 20, 1)
  244.  
  245.             except:
  246.                 traceback.print_exc()
  247.                 send = "Entweder fehlt die Anzahl der Kilometer oder die Eingabe ist ungültig."
  248.                 doSleepDel(bot, update, send, 10, 1)
  249.  
  250.         elif '#qp' == hashtag:
  251.             send = "*QPark TXL TP-Verkaufszeiten:*\n Mo.: 14-16 Uhr/Do.: 20-12 Uhr\n Sollte niemand im Büro sein: 0151 440 394 06"
  252.             doSleepDel(bot, update, send, 40, 1)
  253.  
  254.         elif '#qr' == hashtag:
  255.             send = "Sende QR Code"
  256.  
  257.         elif '#sektor' == hashtag:
  258.             try:
  259.                 sektornummer = int(update.message.text.lower().split()[1])
  260.  
  261.                 with open('SEKTOR.csv') as csvDataFile:
  262.                     csvReader = csv.reader(csvDataFile, delimiter=';')
  263.                     erg = ''
  264.  
  265.                     for row in csvReader:
  266.                         if re.match(str(sektornummer) + '$', row[0]):
  267.                             print(row[1])
  268.                             erg = row[1]
  269.  
  270.                     if erg == '':
  271.                         send = "Dazu gibt es keinen Sektor. Deine Eingabe war: {}.".format(update.message.text)
  272.                     else:
  273.                         send = "Die Nummer {} hat den Sektornamen {}.".format(sektornummer, erg)
  274.                     doSleepDel(bot, update, send, 20, 1)                
  275.  
  276.             except:
  277.                 traceback.print_exc()
  278.                 send = "Fehler. Versuche es noch einmal. Eingabe war: {}\nKorrekte Syntax: #sektor \[Nr.]".format(update.message.text)
  279.                 doSleepDel(bot, update, send, 10, 1)  
  280.  
  281.         elif '#sp' == hashtag:
  282.             send = "[24/7 Spätkäufe](https://goo.gl/JpWr4g)"
  283.             doSleepDel(bot, update, send, 10, 1)
  284.  
  285.         elif '#taxi' == hashtag:
  286.             send = "[Taxi Berlin Bestellung](https://m.taxi4me.net/mobile/index2.html?z=2020#/)"
  287.             doSleepDel(bot, update, send, 10, 1)
  288.  
  289.         elif '#tr' == hashtag:
  290.             send = "[Taxirechner](http://www.taxi-rechner.de/)"
  291.             doSleepDel(bot, update, send, 10, 1)
  292.  
  293.         elif '#txl' == hashtag:
  294.             send = "[TXL Ankünfte](http://www.berlin-airport.de/de/reisende-txl/ankuenfte-und-abfluege/ankuenfte/index.php)"
  295.             doSleepDel(bot, update, send, 40, 1)
  296.  
  297.         elif '#wasch' == hashtag:
  298.             send = "[24/7 Waschanlagen](https://goo.gl/RC211s)"
  299.             doSleepDel(bot, update, send, 10, 1)
  300.  
  301.         elif '#wc' == hashtag:
  302.             send = "[Karte mit Toiletten](https://goo.gl/HS7ZpW)"
  303.             doSleepDel(bot, update, send, 10, 1)
  304.  
  305.         elif '#zob' == hashtag:
  306.             send = "[ZOB Ankünfte](http://zob.berlin/de/fahrgaeste-und-besucher#ankuenfte)"
  307.             doSleepDel(bot, update, send, 30, 1)
  308.  
  309.         else:
  310.             send = "Diesen Befehl kenne ich nicht. Die #liste zeigt alle vorhandenen Befehle."
  311.             doSleepDel(bot, update, send, 15, 1)
  312.  
  313. def format_number_0b(number,format="%0.2f",comma=",",thousand=".",grouplength=3):
  314.     if abs(number) < 10**grouplength:
  315.         if type(number) is str:
  316.             if number == '':
  317.                 number = 0
  318.         f = float(number)
  319.         if f.is_integer():
  320.             return int(f)
  321.         else:
  322.             return (format % (number)).replace(".", comma)
  323.     if format[-1]=="f":
  324.         vor_komma,hinter_komma=(format % number).split(".",-1)
  325.     else:
  326.         vor_komma=format % number
  327.         comma=""
  328.         hinter_komma=""
  329.     #Hier
  330.     anz_leer=0
  331.     for i in vor_komma:
  332.         if i==" ":
  333.             anz_leer+=1
  334.         else:
  335.             break
  336.     vor_komma=vor_komma[anz_leer:]
  337.     #bis hier
  338.  
  339.     len_vor_komma=len(vor_komma)
  340.     for i in range(grouplength,len_vor_komma+(len_vor_komma-1)/(grouplength+1)-(number<0),grouplength+1):
  341.         vor_komma=vor_komma[0:-(i)]+thousand+vor_komma[-(i):]
  342.     if hinter_komma == '00':
  343.         return anz_leer*" "+vor_komma
  344.     else:
  345.         return anz_leer*" "+vor_komma+comma+hinter_komma
  346.    
  347.  
  348. def mN(x):
  349.     if type(x) is str:
  350.         if x == '':
  351.             x = 0
  352.     f = float(x)
  353.     if f.is_integer():
  354.         return int(f)
  355.     else:
  356.         return f
  357.  
  358. def error(bot, update, error):
  359.     """Log Errors caused by Updates."""
  360.     logger.warning('Update "%s" caused error "%s"', update, error)
  361.  
  362. # def filter_chat_id(message):
  363. #     return message.chat_id not in allowed_chat_ids    Filters.chat(-1001302877202),
  364.  
  365. def main():
  366.     # Create the EventHandler and pass it your bot's token.
  367.     updater = Updater("x")
  368.  
  369.     # Get the dispatcher to register handlers
  370.     updater.dispatcher.add_handler(CommandHandler('start', start))
  371.     updater.dispatcher.add_handler(MessageHandler(Filters.text & Filters.entity('hashtag'), hashtag))
  372.  
  373.     # log all errors
  374.     updater.dispatcher.add_error_handler(error)
  375.  
  376.     # Start the Bot
  377.     updater.start_polling(poll_interval = 1.5
  378.         , timeout=5)
  379.  
  380.     # Run the bot until you press Ctrl-C or the process receives SIGINT,
  381.     # SIGTERM or SIGABRT. This should be used most of the time, since
  382.     # start_polling() is non-blocking and will stop the bot gracefully.
  383.     updater.idle()
  384.  
  385.  
  386. if __name__ == '__main__':
  387.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement