Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- #
- """
- """
- from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, InlineQueryHandler, CallbackQueryHandler
- from telegram import InlineQueryResultArticle, InputTextMessageContent, ParseMode, InlineKeyboardButton, InlineKeyboardMarkup
- import logging
- import requests, json
- from uuid import uuid4
- from pytz import timezone
- import datetime
- import psycopg2
- # Enable logging
- logging.basicConfig(
- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
- level=logging.INFO)
- logger = logging.getLogger(__name__)
- telegram_token="237903379:AAHj3_cgvcSnO_u7k5nzpIyDtew6vykAgX0"
- pg_pass = 'jeibzm31'
- valve_key = '3CA60E5A3D1E0193F491AC31FE85C964'
- moscow_timezone = timezone('Europe/Moscow')
- processed_matches = {}
- subscribed_chat_ids = {
- 63675289: True # jkee
- }
- job_queue = None
- active_accounts = [
- {
- 'account_id': 102849623,
- 'name': """Lina's Hot Ass"""
- },
- {
- 'account_id': 33724029,
- 'name': """Dexter Holland"""
- },
- {
- 'account_id': 140194446,
- 'name': """Midrackovich"""
- },
- {
- 'account_id': 34553034,
- 'name': """Morwinyon"""
- },
- {
- 'account_id': 289391160,
- 'name': """MightyNoob"""
- }
- ]
- # global pg connect
- conn = psycopg2.connect("dbname='metrika' user='jkee' host='localhost' port='5433' password='{}'".format(pg_pass))
- # Define a few command handlers. These usually take the two arguments bot and
- # update. Error handlers also receive the raised TelegramError object in error.
- def start(bot, update):
- bot.sendMessage(update.message.chat_id, text="Да, я работаю.")
- def help(bot, update):
- bot.sendMessage(update.message.chat_id, text='Help!')
- def error(bot, update, error):
- logger.warn('Update "%s" caused error "%s"' % (update, error))
- def get_new_matches():
- # dict for unique matches
- new_matches = {}
- for account in active_accounts:
- matches = get_matches(account['account_id'])
- for match in matches:
- match_id = match['match_id']
- if (not processed_matches.has_key(match_id)):
- new_matches[match_id] = match
- new_matches_list = new_matches.values()
- return sorted(new_matches_list, key=lambda match: match['start_time'])
- # can return none if match isn't interesting
- def render_match_info(match_id):
- match_details = get_match_details(match_id)
- participants = ''
- participants_num = 0
- dire = False
- for player in match_details['players']:
- for our_player in active_accounts:
- if (player['account_id'] == our_player['account_id']):
- participants_num += 1
- # update our_side
- dire = isDire(player['player_slot'])
- # update names
- participants += '*' + our_player['name'] + '* '
- participants += ' '
- participants += '{}-{}-{}'.format(player['kills'], player['deaths'], player['assists'])
- participants += '\n'
- if (participants_num <= 1):
- # один нам не интересен, только командные игры!
- return None
- win = (not dire) == match_details['radiant_win']
- time = datetime.datetime.fromtimestamp(match_details['start_time'], moscow_timezone)
- text = ''
- if (win):
- text += '*Втащено!*'
- else:
- text += '*Слито!*'
- text += '\n'
- text += time.strftime('%Y-%m-%d %H:%M:%S') + ' [Dotabuff](http://www.dotabuff.com/matches/{})'.format(match_id)
- text += '\n'
- text += participants
- return text
- def subscribe(bot, update):
- subscribed_chat_ids[update.message.chat_id] = True
- print 'Subscriber: {}'.format(update.message.chat_id)
- bot.sendMessage(update.message.chat_id, text='Подписано!')
- def report_new_matches(bot):
- new_matches = get_new_matches()
- if (len(new_matches) > 0):
- for match in new_matches:
- text = render_match_info(match['match_id'])
- if (text != None):
- for chat_id in subscribed_chat_ids.keys():
- bot.sendMessage(chat_id, text=text, parse_mode='Markdown', disable_web_page_preview=True)
- processed_matches[match['match_id']] = True
- print 'New matches processed. Found {} new matches for {} subscribers'.format(len(new_matches), len(subscribed_chat_ids.keys()))
- def matches(bot, update):
- matches = get_new_matches()
- # todo filtering only new
- for match in matches:
- text = render_match_info(match['match_id'])
- if (text != None):
- bot.sendMessage(update.message.chat_id, text=text, parse_mode='Markdown', disable_web_page_preview=True)
- def isDire(slot):
- return slot & 0x80 > 0
- def get_matches(account_id):
- base_url = 'http://api.steampowered.com/IDOTA2Match_570/GetMatchHistory/v1?key={}&account_id={}&matches_requested=10'
- url = base_url.format(valve_key, account_id)
- result = requests.get(url)
- if (result.status_code == 503):
- # try again
- result = requests.get(url)
- if (result.status_code == 503):
- # try again
- result = requests.get(url)
- result.raise_for_status()
- return result.json()['result']['matches']
- def get_match_details(match_id):
- base_url = 'http://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/v1?key={}&match_id={}'
- url = base_url.format(valve_key, match_id)
- result = requests.get(url)
- if (result.status_code == 503):
- # try again
- result = requests.get(url)
- if (result.status_code == 503):
- # try again
- result = requests.get(url)
- result.raise_for_status()
- return result.json()['result']
- def main():
- # Taking all current games and putting them to processed
- for match in get_new_matches():
- print match['match_id']
- processed_matches[match['match_id']] = True
- print 'Matched processed'
- # removing one for debug
- del processed_matches[2362112039]
- # Create the EventHandler and pass it your bot's token.
- updater = Updater(telegram_token)
- job_queue = updater.job_queue
- # Get the dispatcher to register handlers
- dp = updater.dispatcher
- # on different commands - answer in Telegram
- dp.addHandler(CommandHandler("start", start))
- dp.addHandler(CommandHandler("help", help))
- dp.addHandler(CommandHandler("matches", matches))
- dp.addHandler(CommandHandler("subscribe", subscribe))
- # log all errors
- dp.addErrorHandler(error)
- # set up timer
- job_queue.put(report_new_matches, 10, repeat=True)
- # Start the Bot
- updater.start_polling()
- print 'init done, entering idle state'
- # Run the bot until the you presses Ctrl-C or the process receives SIGINT,
- # SIGTERM or SIGABRT. This should be used most of the time, since
- # start_polling() is non-blocking and will stop the bot gracefully.
- updater.idle()
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement