Advertisement
Guest User

Untitled

a guest
May 14th, 2016
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.09 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4.  
  5. """
  6. """
  7.  
  8. from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, InlineQueryHandler, CallbackQueryHandler
  9. from telegram import InlineQueryResultArticle, InputTextMessageContent, ParseMode, InlineKeyboardButton, InlineKeyboardMarkup
  10. import logging
  11. import requests, json
  12. from uuid import uuid4
  13. from pytz import timezone
  14. import datetime
  15.  
  16. import psycopg2
  17.  
  18. # Enable logging
  19. logging.basicConfig(
  20.         format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
  21.         level=logging.INFO)
  22.  
  23. logger = logging.getLogger(__name__)
  24.  
  25. telegram_token="237903379:AAHj3_cgvcSnO_u7k5nzpIyDtew6vykAgX0"
  26. pg_pass = 'jeibzm31'
  27. valve_key = '3CA60E5A3D1E0193F491AC31FE85C964'
  28.  
  29. moscow_timezone = timezone('Europe/Moscow')
  30.  
  31. processed_matches = {}
  32. subscribed_chat_ids = {
  33.     63675289: True # jkee
  34. }
  35. job_queue = None
  36.  
  37. active_accounts = [
  38.     {
  39.         'account_id': 102849623,
  40.         'name': """Lina's Hot Ass"""
  41.     },
  42.     {
  43.         'account_id': 33724029,
  44.         'name': """Dexter Holland"""
  45.     },
  46.     {
  47.         'account_id': 140194446,
  48.         'name': """Midrackovich"""
  49.     },
  50.     {
  51.         'account_id': 34553034,
  52.         'name': """Morwinyon"""
  53.     },
  54.     {
  55.         'account_id': 289391160,
  56.         'name': """MightyNoob"""
  57.     }
  58. ]
  59.  
  60. # global pg connect
  61. conn = psycopg2.connect("dbname='metrika' user='jkee' host='localhost' port='5433' password='{}'".format(pg_pass))
  62.  
  63.  
  64.  
  65. # Define a few command handlers. These usually take the two arguments bot and
  66. # update. Error handlers also receive the raised TelegramError object in error.
  67. def start(bot, update):
  68.     bot.sendMessage(update.message.chat_id, text="Да, я работаю.")
  69.  
  70.  
  71. def help(bot, update):
  72.     bot.sendMessage(update.message.chat_id, text='Help!')
  73.  
  74.  
  75. def error(bot, update, error):
  76.     logger.warn('Update "%s" caused error "%s"' % (update, error))
  77.  
  78. def get_new_matches():
  79.     # dict for unique matches
  80.     new_matches = {}
  81.     for account in active_accounts:
  82.         matches = get_matches(account['account_id'])
  83.         for match in matches:
  84.             match_id = match['match_id']
  85.             if (not processed_matches.has_key(match_id)):
  86.                 new_matches[match_id] = match
  87.  
  88.     new_matches_list = new_matches.values()
  89.     return sorted(new_matches_list, key=lambda match: match['start_time'])
  90.  
  91. # can return none if match isn't interesting
  92. def render_match_info(match_id):
  93.     match_details = get_match_details(match_id)
  94.  
  95.     participants = ''
  96.     participants_num = 0
  97.     dire = False
  98.  
  99.     for player in match_details['players']:
  100.         for our_player in active_accounts:
  101.             if (player['account_id'] == our_player['account_id']):
  102.                 participants_num += 1
  103.                 # update our_side
  104.                 dire = isDire(player['player_slot'])
  105.                 # update names
  106.                 participants += '*' + our_player['name'] + '*     '
  107.                 participants += ' '
  108.                 participants += '{}-{}-{}'.format(player['kills'], player['deaths'], player['assists'])
  109.                 participants += '\n'
  110.  
  111.     if (participants_num <= 1):
  112.         # один нам не интересен, только командные игры!
  113.         return None
  114.  
  115.     win = (not dire) == match_details['radiant_win']
  116.     time = datetime.datetime.fromtimestamp(match_details['start_time'], moscow_timezone)
  117.    
  118.     text = ''
  119.     if (win):
  120.         text += '*Втащено!*'
  121.     else:
  122.         text += '*Слито!*'    
  123.  
  124.     text += '\n'
  125.     text += time.strftime('%Y-%m-%d %H:%M:%S') + ' [Dotabuff](http://www.dotabuff.com/matches/{})'.format(match_id)
  126.     text += '\n'
  127.     text += participants
  128.  
  129.     return text
  130.  
  131. def subscribe(bot, update):
  132.     subscribed_chat_ids[update.message.chat_id] = True
  133.     print 'Subscriber: {}'.format(update.message.chat_id)
  134.     bot.sendMessage(update.message.chat_id, text='Подписано!')
  135.  
  136. def report_new_matches(bot):
  137.     new_matches = get_new_matches()
  138.     if (len(new_matches) > 0):
  139.         for match in new_matches:
  140.             text = render_match_info(match['match_id'])
  141.             if (text != None):
  142.                 for chat_id in subscribed_chat_ids.keys():
  143.                     bot.sendMessage(chat_id, text=text, parse_mode='Markdown', disable_web_page_preview=True)
  144.             processed_matches[match['match_id']] = True
  145.     print 'New matches processed. Found {} new matches for {} subscribers'.format(len(new_matches), len(subscribed_chat_ids.keys()))
  146.  
  147. def matches(bot, update):
  148.     matches = get_new_matches()
  149.     # todo filtering only new
  150.     for match in matches:
  151.         text = render_match_info(match['match_id'])
  152.         if (text != None):
  153.             bot.sendMessage(update.message.chat_id, text=text, parse_mode='Markdown', disable_web_page_preview=True)
  154.  
  155. def isDire(slot):
  156.     return slot & 0x80 > 0
  157.  
  158. def get_matches(account_id):
  159.     base_url = 'http://api.steampowered.com/IDOTA2Match_570/GetMatchHistory/v1?key={}&account_id={}&matches_requested=10'
  160.     url = base_url.format(valve_key, account_id)
  161.     result = requests.get(url)
  162.     if (result.status_code == 503):
  163.         # try again
  164.         result = requests.get(url)
  165.     if (result.status_code == 503):
  166.         # try again
  167.         result = requests.get(url)
  168.     result.raise_for_status()
  169.     return result.json()['result']['matches']
  170.  
  171. def get_match_details(match_id):
  172.     base_url = 'http://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/v1?key={}&match_id={}'
  173.     url = base_url.format(valve_key, match_id)
  174.     result = requests.get(url)
  175.     if (result.status_code == 503):
  176.         # try again
  177.         result = requests.get(url)
  178.     if (result.status_code == 503):
  179.         # try again
  180.         result = requests.get(url)
  181.     result.raise_for_status()
  182.     return result.json()['result']
  183.  
  184. def main():
  185.  
  186.     # Taking all current games and putting them to processed
  187.     for match in get_new_matches():
  188.         print match['match_id']
  189.         processed_matches[match['match_id']] = True
  190.  
  191.     print 'Matched processed'
  192.  
  193.     # removing one for debug
  194.     del processed_matches[2362112039]
  195.  
  196.     # Create the EventHandler and pass it your bot's token.
  197.     updater = Updater(telegram_token)
  198.     job_queue = updater.job_queue
  199.  
  200.     # Get the dispatcher to register handlers
  201.     dp = updater.dispatcher
  202.  
  203.     # on different commands - answer in Telegram
  204.     dp.addHandler(CommandHandler("start", start))
  205.     dp.addHandler(CommandHandler("help", help))
  206.     dp.addHandler(CommandHandler("matches", matches))
  207.     dp.addHandler(CommandHandler("subscribe", subscribe))
  208.  
  209.     # log all errors
  210.     dp.addErrorHandler(error)
  211.  
  212.     # set up timer
  213.     job_queue.put(report_new_matches, 10, repeat=True)
  214.  
  215.     # Start the Bot
  216.     updater.start_polling()
  217.  
  218.     print 'init done, entering idle state'
  219.  
  220.     # Run the bot until the you presses Ctrl-C or the process receives SIGINT,
  221.     # SIGTERM or SIGABRT. This should be used most of the time, since
  222.     # start_polling() is non-blocking and will stop the bot gracefully.
  223.     updater.idle()
  224.  
  225. if __name__ == '__main__':
  226.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement