示例#1
0
文件: bot.py 项目: MFarelS/ID_AzanBot
def feedback(bot, update):
    ##update.message.reply_text('REPLY pesan ini untuk mengirimkan saran atau melaporkan bugs.\nKETIK dan KIRIM  `/cancel`  untuk membatalkan sesi feedback.\n\n', parse_mode='Markdown', reply_markup=ForceReply())
    ##return FEEDB_MSG
    update.message.reply_text('Gunakan link ke Facebook page kami untuk mengirimkan saran atau melaporkan bugs: https://fb.me/IDAzanBot ', disable_web_page_preview=True)
    
    if not 'test' in DBNAME:
        Botan(BOTAN_TOKEN).track(update.message, event_name='feedback')
示例#2
0
文件: bot.py 项目: MFarelS/ID_AzanBot
def cancel(bot,update):
    update.message.reply_text('Sesi Feedback telah dibatalkan', reply_markup=ReplyKeyboardRemove())
    user = update.message.from_user
    logger.info("First name: {}, Last name: {}, Username: {}, canceled the feedback.".format(user.first_name, user.last_name, user.username))
    return ConversationHandler.END

    if not 'test' in DBNAME:
        Botan(BOTAN_TOKEN).track(update.message, event_name='cancel')
示例#3
0
文件: bot.py 项目: MFarelS/ID_AzanBot
def restart(bot, update):
    bot.send_message(update.message.chat_id, "Bot is restarting...")

    if not 'test' in DBNAME:
        Botan(BOTAN_TOKEN).track(update.message, event_name='restart')

    time.sleep(0.2)
    os.execl(sys.executable, sys.executable, *sys.argv)
示例#4
0
文件: bot.py 项目: MFarelS/ID_AzanBot
def botstat(bot, update):
    cusers_qry_stat_member = db.cusers.find({"fblock": False}).count()
    cusers_qry_stat_mbrzns = db.cusers.find({"fblock": False, "czones_id": {"$ne": None}}).count()
    cusers_qry_stat_mbrntf = db.cusers.find({"fdsble": False, "fblock": False, "czones_id": {"$ne": None}}).count()

    msg = '*[Statistics]*\n'
    msg = '{}Active Subscriber: {}\n'.format(msg, cusers_qry_stat_member)
    msg = '{}Active Subscriber w/ Zone data: {}\n'.format(msg, cusers_qry_stat_mbrzns)
    msg = '{}Active Subscriber w/ Zone data & notification: {}'.format(msg, cusers_qry_stat_mbrntf)

    update.message.reply_text(msg, parse_mode='Markdown')

    if not 'test' in DBNAME:
        Botan(BOTAN_TOKEN).track(update.message, event_name='botstat')
示例#5
0
文件: bot.py 项目: MFarelS/ID_AzanBot
def stop(bot, update):
    chat_id = update.message.chat_id
    doc_cusers_qry = db.cusers.find_one({"_id": chat_id}, {"_id": 1})
    if doc_cusers_qry is not None: 
        cusers_upd = db.cusers.update_one(
                        {"_id": chat_id}, 
                        {"$set": {"fdsble": True}}
                     )

        update.message.reply_text('Notifikasi telah dinonaktifkan. Notifikasi dapat Anda aktifkan kembali dengan mengirimkan perintah  /start  .')
    else:
        update.message.reply_text('Error! Setting Zona belum dilakukan. Gunakan perintah  /setting  untuk melakukan setting Zona.')
    
    if not 'test' in DBNAME:
        Botan(BOTAN_TOKEN).track(update.message, event_name='stop')
示例#6
0
文件: bot.py 项目: MFarelS/ID_AzanBot
def today(bot, update):
    chat_id = update.message.chat_id
    doc_cusers_qry = db.cusers.find_one({"_id": chat_id})
    if doc_cusers_qry is not None:
        lv_zones = doc_cusers_qry.get('czones_id')
        if lv_zones is not None:
            msg = prayertime(lv_zones)
            update.message.reply_text(msg, parse_mode='Markdown', disable_web_page_preview=True)
        else:
            update.message.reply_text('Setting Zona belum dilakukan.\nGunakan perintah  /setting  untuk melakukan setting Zona.')   

    else:
        update.message.reply_text('Setting Zona belum dilakukan.\nGunakan perintah  /setting  untuk melakukan setting Zona.')

    if not 'test' in DBNAME:
        Botan(BOTAN_TOKEN).track(update.message, event_name='today')
示例#7
0
文件: bot.py 项目: MFarelS/ID_AzanBot
def help(bot, update):
    msg = "Assalaamu'alaikum\n\n"
    msg = '{}Berikut ini daftar perintah yang dapat Anda berikan pada bot:\n\n'.format(msg)
    msg = '{}/start  - untuk mengaktifkan bot dan notifikasi. Gunakan juga perintah ini untuk mengaktifkan kembali notifikasi jika sebelumnya Anda telah menggunakan perintah  /stop  .\n\n'.format(msg)
    msg = '{}/stop  - untuk menonaktifkan notifikasi dari bot. Anda masih tetap dapat mempergunakan semua perintah yang ada, seperti  /today  atau  /prayerinfo  untuk informasi jadwal salat hari ini.\n\n'.format(msg)
    msg = '{}/help  - untuk menampilkan menu help ini.\n\n'.format(msg)
    msg = '{}/next  - untuk menampilkan informasi berapa lama ke notifikasi yang berikutnya.\n\n'.format(msg)
    msg = '{}/n  - alias untuk  /next  . Memiliki fungsi yang sama dengan perintah  /next  .\n\n'.format(msg)
    msg = '{}/setting  - menu setting. Set zona Anda, atur notifikasi untuk notifikasi waktu Imsak dan Terbit dan pengaturan fungsi Reminder.\n\n'.format(msg)
    msg = "{}/today  - meminta bot untuk mengirimkan jadwal waktu salat hari ini untuk zona Anda.\n\n".format(msg)
    msg = "{}/t  - alias untuk  /today  . Memiliki fungsi yang sama dengan perintah  /today  .\n\n".format(msg)
    msg = "{}/prayerinfo  - meminta bot untuk mengirimkan jadwal waktu salat hari ini untuk zona tertentu.\n\n".format(msg)
    msg = '{}/feedback  - input dan saran dari Anda sangat kami nantikan. Gunakan pula perintah ini untuk melaporkan bugs yang Anda jumpai.\n\n'.format(msg)
    #msg = '{}`/cancel`  - untuk membatalkan sesi feedback. Perintah ini hanya akan aktif jika Anda berada di dalam sesi feedback.\n\n'
    msg = '{}/rateme  - berikan rating Anda untuk bot ini.\n\n'.format(msg)
    update.message.reply_text(msg, parse_mode='Markdown')

    if not 'test' in DBNAME:
        Botan(BOTAN_TOKEN).track(update.message, event_name='help')
示例#8
0
文件: bot.py 项目: MFarelS/ID_AzanBot
def start(bot, update):
    chat_id = update.message.chat_id
    doc_cusers_qry = db.cusers.find_one({"_id": chat_id}, {"_id": 1})
    if doc_cusers_qry is not None: 
        cusers_upd = db.cusers.update_one(
                        {"_id": chat_id}, 
                        {"$set": {"fdsble": False, "fblock": False }}  
                     )
    
    msg = "Assalaamu'alaikum\n\n"
    msg = '{}Silakan melakukan setting Zona terlebih dahulu dengan mengirimkan perintah  /setting  .\n\n'.format(msg)
    msg = '{}Notifikasi akan dikirim otomatis saat memasuki waktu salat.\n\n'.format(msg)
    msg = '{}Gunakan perintah  /today  untuk mengetahui jadwal waktu salat hari ini bagi zona Anda atau perintah  '.format(msg)
    msg = '{}/prayerinfo  untuk mendapatkan jadwal waktu salat zona-zona lainnya.\n\n'.format(msg)
    msg = '{}Untuk informasi perintah-perintah lain yang dapat diberikan pada bot, Anda dapat mengirimkan  /help  .\n\n'.format(msg)
    msg = '{}Follow kami di Facebook page -  https://fb.me/IDAzanBot  \n'.format(msg)
    #msg = '{}\n'.format(msg)
    #msg = '{}ID_AzanBot menggunakan data waktu salat dari Kementerian Agama Republik Indonesia.'.format(msg)
    update.message.reply_text(msg, disable_web_page_preview=True)

    if not 'test' in DBNAME:
        Botan(BOTAN_TOKEN).track(update.message, event_name='start')
示例#9
0
文件: bot.py 项目: MFarelS/ID_AzanBot
def setting(bot, update):
    chat_id = update.message.chat_id
    doc_cusers_qry = db.cusers.find_one({"_id": chat_id})
    lv_notiflog = False

    if doc_cusers_qry == None:
        cusers_ins = db.cusers.insert_one(
                        {"_id": chat_id, 
                         "czones_id": None, 
                         "fblock": False, 
                         "fdaily": False, 
                         "fdsble": False, 
                         "frmndr": 0, 
                         "fsyurk": False, 
                         "fimsak": False}
                     )

        lv_notiflog = True

    reply_markup = InlineKeyboardMarkup(settingmenu(chat_id))
    update.message.reply_text('Setting:', reply_markup=reply_markup)

    if lv_notiflog == True:
        user = update.message.from_user
        lv_subject = ''
        if 'test' in DBNAME:
            lv_subject = 'TEST '

        logger.info("[New User] Chat ID: {}, First name: {}, Last name: {}, Username: {}.".format(chat_id, user.first_name, user.last_name, user.username))

        try:
            bot.send_message(chat_id=LOG_CHATID, text='[{}New User] Chat ID: {}, First name: {}, Last name: {}, Username: {}'.format(lv_subject, chat_id, user.first_name, user.last_name, user.username))
        
        except TelegramError as e:
            logger.error('[TelegramError] Notification of New User {} caused error: {}'.format(chat_id, e.message))
    
    if not 'test' in DBNAME:
        Botan(BOTAN_TOKEN).track(update.message, event_name='setting')
示例#10
0
    def __init__(self, telegram, botan):
        if botan:
            from telegram.contrib.botan import Botan
            self.botan = Botan(botan)

        self.updater = Updater(telegram)
        dp = self.updater.dispatcher
        dp.add_handler(CommandHandler('start', self.start, pass_args=True))
        dp.add_handler(CommandHandler('close', self.start))
        dp.add_handler(CommandHandler('previous', self.get_previous))
        dp.add_handler(CommandHandler('next', self.get_next))
        dp.add_handler(CommandHandler('help', self.help))
        dp.add_handler(CommandHandler('about', self.about))
        dp.add_handler(CommandHandler('TOP', self.top))
        dp.add_handler(CommandHandler('find', self.search))
        dp.add_handler(CommandHandler('random', self.random))
        dp.add_handler(CommandHandler('EN', self.engl))
        dp.add_handler(CommandHandler('RU', self.russ))
        dp.add_handler(CallbackQueryHandler(self.filter_for_inline))
        dp.add_handler(InlineQueryHandler(self.inline_search))
        dp.add_handler(ChosenInlineResultHandler(self.inline_picture))
        dp.add_handler(MessageHandler([Filters.text], self.command_filter))
        dp.add_handler(MessageHandler([Filters.command], self.unknow))

        #dp.addErrorHandler(self.error)
        self.result = {}
        self.count = {}
        self.photo_count = {}
        self.photo = {}
        self.answer = {}
        self.search_query = {}
        self.like = {}
        self.offset = {}
        self.podbor = {}
        self.choosen_locale = {}
        self.inline = {}
        self.inline_list = {}
示例#11
0
文件: bot.py 项目: MFarelS/ID_AzanBot
def chatid(bot, update):
    chat_id = update.message.chat_id
    update.message.reply_text(str(chat_id))

    if not 'test' in DBNAME:
        Botan(BOTAN_TOKEN).track(update.message, event_name='chatid')
示例#12
0
 def test_wrong_endpoint(self):
     botan = Botan(self.token)
     botan.url_template = 'https://api.botaaaaan.io/traccc?token={token}&uid={uid}&name={name}'
     message = MessageMock(self._chat_id)
     result = botan.track(message, 'named event')
     self.assertFalse(result)
示例#13
0
文件: bot.py 项目: MFarelS/ID_AzanBot
def rateme(bot, update):
    update.message.reply_text('Ikuti link berikut untuk memberi rating: {}'.format(STOREBOT_REVIEW_URL), disable_web_page_preview=True)

    if not 'test' in DBNAME:
        Botan(BOTAN_TOKEN).track(update.message, event_name='rateme')
示例#14
0
文件: bot.py 项目: MFarelS/ID_AzanBot
def prayerinfo(bot, update):
    reply_markup = InlineKeyboardMarkup(prayerinfomenu())
    update.message.reply_text('Waktu Salat Hari Ini.\n\nPilih propinsi:', reply_markup=reply_markup)

    if not 'test' in DBNAME:
        Botan(BOTAN_TOKEN).track(update.message, event_name='prayerinfo')
示例#15
0
文件: bot.py 项目: MFarelS/ID_AzanBot
def next(bot, update):
    chat_id = update.message.chat_id
    doc_cusers_qry = db.cusers.find_one({"_id": chat_id})
    if doc_cusers_qry is not None:
        lv_zones = doc_cusers_qry.get('czones_id')
        if lv_zones is not None:
            doc_czones_qry = db.czones.find_one({"_id": lv_zones, "fxpara": {"$ne": "default"}})
            lv_ftzone = doc_czones_qry.get('ftzone')
            lv_txzone = ' '
            
            if lv_ftzone == 7:
                lv_txzone = 'WIB'
            elif lv_ftzone == 8:
                lv_txzone = 'WITA'
            elif lv_ftzone == 9:
                lv_txzone = 'WIT'

            utctime = datetime.datetime.utcnow()
            localtime = utctime + datetime.timedelta(hours = lv_ftzone)
            localtime = localtime.replace(hour=0, minute=0, second=0, microsecond=0)

            #Getting midnight of localtime
#            localtime = localtime.replace(hour=0)

            #Getting utctime for midnight of localtime
#            utcbegtime = localtime + datetime.timedelta(hours = -1*lv_ftzone)
#            utcendtime = utcbegtime + datetime.timedelta(hours = 24)

            csched_qry = db.csched.find({"_id": {"$gt": utctime}, "fazfor.czones_id": lv_zones}).sort("_id", 1)
            
            msg = ''

            for doc_csched_qry in csched_qry:
                for lv_fazfor in doc_csched_qry['fazfor']:
                    if lv_fazfor.get('czones_id') == lv_zones:
                        localtime = doc_csched_qry.get('_id')
                        lv_diffs = (localtime - utctime).total_seconds()
                        localtime = localtime + datetime.timedelta(hours = lv_ftzone)                      
                        msg = '{}`{} - {} {}`\n\n'.format(msg, lv_fazfor.get('ftypes'), localtime.strftime('%H:%M'), lv_txzone)
                        break
                break

            #Hijri function
            hijritime = HijriDate(localtime.date().year, localtime.date().month, localtime.date().day, gr=True)

            doc_chijri_qry = db.chijri.find_one({"_id": int(hijritime.month)})
            lv_orihijriday = hijritime.day
            hijritime.day = hijritime.day + doc_chijri_qry.get('fadjst')
            if int(hijritime.day) == 30:
                if doc_chijri_qry.get('f29flg') == True:
                    hijritime.day = 1
                    if hijritime.month == 12:
                        hijritime.month = 1
                        hijritime.year = hijritime.year + 1
                    else:
                        hijritime.month = hijritime.month + 1
            elif int(lv_orihijriday) == 1:
                if int(hijritime.month) == 1:
                    doc_chijri_qry = db.chijri.find_one({"_id": 12})
                else:
                    doc_chijri_qry = db.chijri.find_one({"_id": int(hijritime.month)-1})

                if doc_chijri_qry.get('f30flg') == True:
                    hijritime.day = 30
                    if int(hijritime.month) == 1:
                        hijritime.month = 12
                        hijritime.year = hijritime.year - 1
                    else:
                        hijritime.month = hijritime.month - 1
            #End of Hijri function

            msg = '{}_{}, {} {} {} | '.format(msg, LOCAL_DAY[localtime.weekday()], localtime.day, LOCAL_MONTH[localtime.month], localtime.year)
            msg = '{}{} {} {}\n'.format(msg, int(hijritime.day), HIJRI_MONTH[int(hijritime.month)], int(hijritime.year))
            msg = '{}{} - {}_'.format(msg, doc_czones_qry.get('fdescr'), doc_czones_qry.get('fstate'))
            
            lv_diffh = int(lv_diffs / 3600)
            lv_diffm = int((lv_diffs % 3600) / 60) + ((lv_diffs % 3600) % 60 > 0)
            if lv_diffm == 60:
                lv_diffm = 0
                lv_diffh += 1

            if lv_diffh == 0 and lv_diffm > 0:
                msg = '`{} menit menuju waktu `{}'.format(lv_diffm, msg)
            elif lv_diffh == 0 and lv_diffm == 0:
                msg = '`Tepat saat waktu `{}'.format(msg)
            elif lv_diffh > 0 and lv_diffm == 0:
                msg = '`{} jam menuju waktu `{}'.format(lv_diffh, msg)
            elif lv_diffh > 0 and lv_diffm > 0:    
                msg = '`{} jam dan {} menit menuju waktu `{}'.format(lv_diffh, lv_diffm, msg)

            update.message.reply_text(msg, parse_mode='Markdown')
        else:
            update.message.reply_text('Setting Zona belum dilakukan.\nGunakan perintah  /setting  untuk melakukan setting Zona.')   

    else:
        update.message.reply_text('Setting Zona belum dilakukan.\nGunakan perintah  /setting  untuk melakukan setting Zona.')

    if not 'test' in DBNAME:
        Botan(BOTAN_TOKEN).track(update.message, event_name='next')
示例#16
0
from myinstants import search_instants

# Enable logging
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO)

LOGGER = logging.getLogger(__name__)

# Load config file
with open('config.json') as config_file:
    CONFIGURATION = json.load(config_file)

# Create a Botan tracker object
BOTAN = Botan(CONFIGURATION["botan_token"])


def start(bot, update):
    """Start command handler"""
    bot.sendMessage(update.message.chat_id,
                    text='Hi!\nYou can use this bot in any chat, just type '
                    '@myinstantsbot query message\nEnjoy!')


def help_command(bot, update):
    """Help command"""
    bot.sendMessage(update.message.chat_id,
                    text='This bot search sounds in myinstants.com\n'
                    'You can use it in any chat, just type '
                    '@myinstantsbot query message')
示例#17
0
from flask import Flask, request, redirect

# Enable logging
logging.basicConfig(
    filename='/home/gaiar/projects/forwardbot/forwardbot.log',
    filemode='a',
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.DEBUG)

logger = logging.getLogger(__name__)
pocket_instance = Pocket(tokens.POCKET_CONSUMER_TOKEN,
                         tokens.POCKET_ACCESS_TOKEN)
auth_token = ""
db = ForwardBotDatabase('botusers.db')
botan = Botan(tokens.BOTAN_TOKEN)

users = {}

#updater = Updater(tokens.TELEGRAM_TOKEN)

bot = Bot(tokens.TELEGRAM_TOKEN)
update_queue = Queue()

dp = Dispatcher(bot, update_queue)

app = Flask(__name__)


def start(bot, update, args):
    telegram_user = update.message.from_user
示例#18
0
 def test_wrong_message(self):
     botan = Botan(self.token)
     message = MessageMock(self._chat_id)
     message = delattr(message, 'chat_id')
     result = botan.track(message, 'named event')
     self.assertFalse(result)
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

import json
from telegram.ext import Updater
from telegram.contrib.botan import Botan

from game_manager import GameManager
from database import db
import user_setting  # required to generate db mapping

db.bind('sqlite', 'uno.sqlite3', create_db=True)
db.generate_mapping(create_tables=True)

gm = GameManager()
with open("config.json","r") as f:
    config = json.loads(f.read())
updater = Updater(token=config.get("token"), workers=config.get("workers", 32))
dispatcher = updater.dispatcher

if config.get("botan_token"):
    botan = Botan(config.get("botan_token"))
else:
    botan = None
示例#20
0
class ChinaBot:
    ut = {'help':
                {'RU':('Список комманд:\n'
                       '/TOP - Подборка товаров с наивысшим рейтингом\n'
                       '/random - Показ случайного товара\n'
                       '/find - Поиск товаров по названию\n'
                       '/EN - Изменить локализацию на En\n'
                       '/RU - Изменить локализацию на Ru\n'
                       '/help - Список комманд\n'
                       '/about - О боте...\n'
                       'Для изменения сортировки в подборках нажмите <, находясь на первой позиции'),

                'EN':('List of commands:\n'
                       '/TOP - Only best products\n'
                       '/random - Random product\n'
                       '/find - Find products by name\n'
                       '/EN - Change localisation En\n'
                       '/RU - Change localisation Ru\n'
                       '/help - List of commands\n'
                       '/about - About...\n'
                       'If you want change sorting of the results in sets press < at first position')},
          'product':
              {'RU':[u'Наименование',u'Магазин',u'Рейтинг',u'Цена',u'ЗАКАЗАТЬ'],
               'EN':['Item','Store','Rating','Cost','Purchase']},
          'hello':
              {'RU':u'Привет! Меня зовут @VapesBot, я помогу Вам найти электронные сигареты и аксессуары по доступным ценам с возможностью бесплатной доставки по всему миру.',
               'EN':'Hello! My name is @VapesBot, I can find best offers of E-cigs and accessories for you, best prices and free world-wide delivery.'},
          'hello_lang':
              {'RU':(u'\nПривет! Меня зовут @VapesBot, я помогу Вам найти электронные сигареты и аксессуары по доступным ценам с возможностью бесплатной доставки по всему миру.\n'
                     u'Для начала, необходимо выбрать язык интерфейса.\n'),
               'EN':('Hello! My name is @VapesBot, I can find best offers of E-cigs and accessories for you, best prices and free world-wide delivery.\n'
                     'Please, choose localisation.\n')},
          'main_keyboard':
              {'RU':['TOP ', u'Наугад ', u'Поиск ', u'Помощь '],
               'EN':['TOP ', 'Random ', 'Find ', 'Help ']},
          'try_search':
              {'RU':u'Попробовать мой поиск ',
               'EN':'Try my in-line search '},
          'try_search_text':
              {'RU':u'Введите ключевые слова для поиска товаров по названию, также, Вы можете использовать встроенный механизм поиска в любом чате, обратившись к боту через @ChinaVapesBot',
               'EN':'Enter keywords to search products by name or use in-line search with @ChinaVapesBot in any chat'},
          'selection':
              {'RU':u'Работа с подборкой %s была завершена, спасибо ',
               'EN':'Work with selection %s has been completed, thanks '},
          'live_here':
              {'RU':u'Я живу здесь ',
               'EN':'I live HERE '},
          'not_find':
              {'RU':u'Извините, мне нечего Вам показать ',
               'EN':'Sorry, nothing found '},
          'other':
              {'RU':[u'Не жмакайте мне там, щекотно ', u'Отложил в чатик ', u'Извините, но мне туда нельзя ', u'Произведена смена сортировки по цене '],
               'EN':['I tickled ', 'I kept in chat ', "Sorry, I can't do this ", 'Sorting by cost has been changed ']},
          'of':
              {'RU':u' ИЗ ',
               'EN':' OF '}}

    def __init__(self, telegram, botan):
        if botan:
            from telegram.contrib.botan import Botan
            self.botan = Botan(botan)

        self.updater = Updater(telegram)
        dp = self.updater.dispatcher
        dp.add_handler(CommandHandler('start', self.start, pass_args=True))
        dp.add_handler(CommandHandler('close', self.start))
        dp.add_handler(CommandHandler('previous', self.get_previous))
        dp.add_handler(CommandHandler('next', self.get_next))
        dp.add_handler(CommandHandler('help', self.help))
        dp.add_handler(CommandHandler('about', self.about))
        dp.add_handler(CommandHandler('TOP', self.top))
        dp.add_handler(CommandHandler('find', self.search))
        dp.add_handler(CommandHandler('random', self.random))
        dp.add_handler(CommandHandler('EN', self.engl))
        dp.add_handler(CommandHandler('RU', self.russ))
        dp.add_handler(CallbackQueryHandler(self.filter_for_inline))
        dp.add_handler(InlineQueryHandler(self.inline_search))
        dp.add_handler(ChosenInlineResultHandler(self.inline_picture))
        dp.add_handler(MessageHandler([Filters.text], self.command_filter))
        dp.add_handler(MessageHandler([Filters.command], self.unknow))

        #dp.addErrorHandler(self.error)
        self.result = {}
        self.count = {}
        self.photo_count = {}
        self.photo = {}
        self.answer = {}
        self.search_query = {}
        self.like = {}
        self.offset = {}
        self.podbor = {}
        self.choosen_locale = {}
        self.inline = {}
        self.inline_list = {}

    def logger_wrap(self, message, command):
        if self.botan:
            self.botan.track(
                message=message,
                event_name=command
            )
        user = message.from_user
        logger.info(u'%s from %s @%s %s' % (message.text[0:20],
                                            user.first_name,
                                            user.username,
                                            user.last_name))

    def product_wrap(self, bot, update, args):
        products = None
        try:
            if args == 'TOP_Down':
                products = db.query(Product).filter_by(score=5).order_by(Product.product_price_u.desc()).all()
            elif args == 'Random':
                count = db.query(Product).count()
                products = db.query(Product).filter_by(id=random.randint(1, count)).limit(10).all()
            elif args == 'Search_Down':
                string = str(self.search_query[str(update.message.chat_id)])
                products = db.query(Product).filter(Product.product_name.contains("%" + string + "%")).order_by(Product.product_price_u.desc()).all()
            elif args == 'Search_Inline':
                string = str(update.inline_query.query)
                products = db.query(Product).filter(Product.product_name.contains("%" + string + "%")).order_by(Product.product_price_u.desc()).all()
            elif args == 'ID':
                try: string = str(update.chosen_inline_result.result_id)
                except: string = self.answer[str(update.callback_query.inline_message_id)]
                products = db.query(Product).filter(Product.product_id == int(string))

        except Exception as e:
            logger.exception(e)
        if args == 'Search_Inline':
            return products
        elif args == 'ID':
            return self.good_view(bot, update, products, args)
        else:
            return self.good_view(bot, update, products, args=None)

    def if_discount(self, str):
        if str == u'0%':
            return ''
        else:
            return u' 🔥 -'+str+''

    def good_view(self, bot, update, products, args):
        final = None
        if products:
            if args == 'Search_Inline':
                user_id = str(update.inline_query.from_user.id)
                locale = self.choosen_locale[user_id]
                if locale == 'RU':
                    final = [u'*%s*: ' % self.ut['product'][locale][0] + products.product_name + '\n'
                             u'*%s*: ' % self.ut['product'][locale][1] + str(products.product_store_title) + '\n'
                             u'*%s*: ' % self.ut['product'][locale][2] + u'⭐' * int(products.score) + '\n'
                             u'*%s*: ' % self.ut['product'][locale][3] + str(products.product_price_r) + u' РУБ' + self.if_discount(str(products.product_discount))+'\n'
                             u'[%s]' % self.ut['product'][locale][4] + '(' + products.partner_url + ')\n']
                elif locale == 'EN':
                    final = [u'*%s*: ' % self.ut['product'][locale][0] + products.product_name + '\n'
                             u'*%s*: ' % self.ut['product'][locale][1] + str(products.product_store_title) + '\n'
                             u'*%s*: ' % self.ut['product'][locale][2] + u'⭐' * int(products.score) + '\n'
                             u'*%s*: ' % self.ut['product'][locale][3] + str(products.product_price_u) + ' USD' + self.if_discount(str(products.product_discount))+'\n'
                             u'[%s]' % self.ut['product'][locale][4] + '(' + products.partner_url + ')\n']
            elif args == 'ID':
                try:
                    user_id = str(update.chosen_inline_result.from_user.id)
                except:
                    user_id = str(update.callback_query.from_user.id)
                locale = self.choosen_locale[user_id]
                if locale == 'RU':
                    final = [u'*%s*: ' % self.ut['product'][locale][0] + products[0].product_name + '\n'
                             u'*%s*: ' % self.ut['product'][locale][1] + str(products[0].product_store_title) + '\n'
                             u'*%s*: ' % self.ut['product'][locale][2] + u'⭐' * int(products[0].score) + '\n'
                             u'*%s*: ' % self.ut['product'][locale][3] + str(products[0].product_price_r) + u' РУБ' + self.if_discount(str(products[0].product_discount))+'\n'
                             u'[%s]' % self.ut['product'][locale][4] + '(' + products[0].partner_url + ')\n']
                elif locale == 'EN':
                    final = [u'*%s*: ' % self.ut['product'][locale][0] + products[0].product_name + '\n'
                             u'*%s*: ' % self.ut['product'][locale][1] + str(products[0].product_store_title) + '\n'
                             u'*%s*: ' % self.ut['product'][locale][2] + u'⭐' * int(products[0].score) + '\n'
                             u'*%s*: ' % self.ut['product'][locale][3] + str(products[0].product_price_u) + ' USD' + self.if_discount(str(products[0].product_discount))+'\n'
                             u'[%s]' % self.ut['product'][locale][4] + '(' + products[0].partner_url + ')\n']
                self.photo[str(products[0].product_id)] = products[0].product_other_picture.split('|')
                return final
            else:
                if update.message:
                    id = str(update.message.message_id)
                    user_id = str(update.message.from_user.id)
                elif update.callback_query:
                    id = str(update.callback_query.message.message_id)
                    user_id = str(update.callback_query.from_user.id)
                locale = self.choosen_locale[user_id]
                self.photo[id] = []
                for product in products:
                    self.photo[id].append(product.product_other_picture.split('|'))
                if locale == 'RU':
                    final = [u'*%s*: ' % self.ut['product'][locale][0] + product.product_name + '\n'
                             u'*%s*: ' % self.ut['product'][locale][1] + str(product.product_store_title) + '\n'
                             u'*%s*: ' % self.ut['product'][locale][2] + u'⭐'*int(product.score) + '\n'
                             u'*%s*: ' % self.ut['product'][locale][3] + str(product.product_price_r) + u' РУБ' + self.if_discount(str(product.product_discount))+'\n'
                             u'[%s]' % self.ut['product'][locale][4] + '('+product.partner_url + ')\n' for product in products]
                elif locale == 'EN':
                    final = [u'*%s*: ' % self.ut['product'][locale][0] + product.product_name + '\n'
                             u'*%s*: ' % self.ut['product'][locale][1] + str(product.product_store_title) + '\n'
                             u'*%s*: ' % self.ut['product'][locale][2] + u'⭐'*int(product.score) + '\n'
                             u'*%s*: ' % self.ut['product'][locale][3] + str(product.product_price_u) + ' USD' + self.if_discount(str(product.product_discount))+'\n'
                             u'[%s]' % self.ut['product'][locale][4] + '('+product.partner_url + ')\n' for product in products]
            return final

    def start(self, bot, update, args):
        try:
            self.logger_wrap(update.message, 'start')
            chat_id = str(update.message.chat_id)
            user_id = str(update.message.from_user.id)
        except:
            self.logger_wrap(update.callback_query.message, 'start')
            chat_id = str(update.callback_query.message.chat_id)
            user_id = str(update.callback_query.message.from_user.id)
        try:
            self.choosen_locale[user_id]
            local = self.choosen_locale[user_id]
            custom_keyboard = [[self.ut['main_keyboard'][local][0] + u'⭐', self.ut['main_keyboard'][local][1] + u'🎲'],
                               [self.ut['main_keyboard'][local][2] + u'🔎', self.ut['main_keyboard'][local][3] + u'📙']]
            reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard, resize_keyboard=True)
            bot.sendMessage(chat_id, text=self.ut['hello'][self.choosen_locale[user_id]],
                            parse_mode=ParseMode.MARKDOWN, reply_markup=reply_markup)
        except:
            try:
                if args[0] == 'from_inline':
                    self.inline[chat_id] = 1
            except:
                self.inline[chat_id] = 0
            custom_keyboard = [[u'🇷🇺', u'🇬🇧']]
            reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard, resize_keyboard=True)
            bot.sendMessage(chat_id, text=(self.ut['hello_lang']['EN']+self.ut['hello_lang']['RU']), parse_mode=ParseMode.MARKDOWN, reply_markup=reply_markup)
        self.del_previous(bot, update)

    def engl(self, bot, update):
        self.choosen_locale[str(update.message.from_user.id)] = 'EN'
        custom_keyboard = [[self.ut['main_keyboard']['EN'][0] + u'⭐', self.ut['main_keyboard']['EN'][1] + u'🎲'],
                           [self.ut['main_keyboard']['EN'][2] + u'🔎', self.ut['main_keyboard']['EN'][3] + u'📙']]
        if self.inline[str(update.message.chat_id)] == 1:
            reply_markup = telegram.InlineKeyboardMarkup([[telegram.InlineKeyboardButton(text='Return to chat', switch_inline_query='')]])
        else:
            reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard, resize_keyboard=True)
        bot.sendMessage(update.message.chat_id, text=u'Language has been set EN 😎', reply_markup=reply_markup)
        self.del_previous(bot, update)
        self.start(bot, update, args=None)
        self.help(bot, update)


    def russ(self, bot, update):
        self.choosen_locale[str(update.message.from_user.id)] = 'RU'
        custom_keyboard = [[self.ut['main_keyboard']['RU'][0] + u'⭐', self.ut['main_keyboard']['RU'][1] + u'🎲'],
                           [self.ut['main_keyboard']['RU'][2] + u'🔎', self.ut['main_keyboard']['RU'][3] + u'📙']]
        if self.inline[str(update.message.chat_id)] == 1:
            reply_markup = telegram.InlineKeyboardMarkup([[telegram.InlineKeyboardButton(text='Return to chat', switch_inline_query='')]])
        else:
            reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard, resize_keyboard=True)
        bot.sendMessage(update.message.chat_id, text=u'Язык был установлен RU 😎', reply_markup=reply_markup)
        #bot.sendVideo(update.message.chat_id, 'https://www.youtube.com/watch?v=0i0FR4LsysU')
        #bot.sendMessage(update.message.chat_id, text='https://www.youtube.com/watch?v=0i0FR4LsysU', reply_markup=reply_markup)
        self.del_previous(bot, update)
        self.start(bot, update, args=None)
        self.help(bot, update)

    def help(self, bot, update):
        self.logger_wrap(update.message, 'help')
        try:
            local = self.choosen_locale[str(update.message.from_user.id)]
        except:
            self.start(bot, update, args=None)
            return
        bot.sendMessage(update.message.chat_id, text=self.ut['help'][local])
        self.del_previous(bot, update)

    def about(self, bot, update):
        self.logger_wrap(update.message, 'about')
        try:
            local = self.choosen_locale[str(update.message.from_user.id)]
        except:
            self.start(bot, update, args=None)
            return
        bot.sendMessage(update.message.chat_id, text=self.ut['hello'][local], parse_mode=ParseMode.MARKDOWN)
        self.del_previous(bot, update)

    def command_filter(self, bot, update):
        self.logger_wrap(update.message, 'command_filter')
        if update.message.text == u'🇷🇺':
            self.russ(bot,update)
            return
        elif update.message.text == u'🇬🇧':
            self.engl(bot,update)
            return
        try:
            locale = self.choosen_locale[str(update.message.from_user.id)]
        except:
            self.start(bot, update, args=None)
            return
        if update.message.text == self.ut['main_keyboard'][locale][0] + u'⭐':
            self.top(bot, update)
        elif update.message.text == self.ut['main_keyboard'][locale][1] + u'🎲':
            self.random(bot, update)
        elif update.message.text == self.ut['main_keyboard'][locale][2] + u'🔎':
            self.search(bot, update)
        elif update.message.text == self.ut['main_keyboard'][locale][3] + u'📙':
            self.help(bot, update)
        elif len(update.message.text) < 50:
            self.do_search(bot, update)
        else:
            self.del_previous(bot, update)

    def search(self, bot, update):
        #self.logger_wrap(update.message, 'search')
        try:
            locale = self.choosen_locale[str(update.message.from_user.id)]
        except: self.start(bot, update, args=None)
        keyboard = telegram.InlineKeyboardMarkup([[telegram.InlineKeyboardButton(text=self.ut['try_search'][locale]+u'😎', switch_inline_query='ego')]])
        bot.sendMessage(update.message.chat_id, text=self.ut['try_search_text'][locale],
                        parse_mode=ParseMode.MARKDOWN, reply_markup=keyboard)
        self.del_previous(bot, update)

    def del_previous(self, bot, update):
        if update.message:
            chat_id = str(update.message.chat_id)
        elif update.callback_query:
            chat_id = str(update.callback_query.message.chat_id)
        try:
            if update.message:
                bot.editMessageText(text=self.ut['selection'][self.choosen_locale[chat_id]] % self.podbor[chat_id][0] + u'😊',
                                    chat_id=chat_id, message_id=str(int(self.podbor[chat_id][1])+self.offset[chat_id]), parse_mode=ParseMode.MARKDOWN)
            self.photo_count[chat_id].__delitem__(self.podbor[chat_id][1])
            self.result.__delitem__(self.podbor[chat_id][1])
            self.photo.__delitem__(self.podbor[chat_id][1])
            self.count.__delitem__(self.podbor[chat_id][1])
        except: pass

    def inline_search(self, bot, update):
        if update.inline_query:
            if update.inline_query.offset == 'next_page':
                self.pagination(bot, update)
                return
            results = list()
            try:
                locale = self.choosen_locale[str(update.inline_query.from_user.id)]
            except:
                bot.answerInlineQuery(update.inline_query.id, results, switch_pm_text='Please visit to me and set localisation '+u'😊', cache_time=1,
                                      switch_pm_parameter='from_inline')
                return
            user = update.inline_query.from_user
            query = update.inline_query.query
            keyboard = self.do_keybord(1, 5, 'do_picture_inline', locale)
            if query:
                logger.info('Inline: %s from %s @%s %s' % (query, user.first_name, user.username, user.last_name))
                if re.findall(r'[^A-Za-z0-9-\s]+', query):
                    return
                products = self.product_wrap(bot, update, "Search_Inline")
                if products:
                    if locale == 'RU':
                        for product in products:
                            results.append(InlineQueryResultArticle(id=product.product_id, title=product.product_name,
                                                                    description=u'⭐'*int(product.score)+u'  💵   '+str(product.product_price_r)+u' РУБ'+ self.if_discount(str(product.product_discount)),
                                                                    thumb_url=product.product_picture, input_message_content=InputTextMessageContent(u''.join(self.good_view(bot, update, product, 'Search_Inline')[0]),
                                                                    parse_mode=ParseMode.MARKDOWN), reply_markup=keyboard))
                    elif locale == 'EN':
                        for product in products:
                            results.append(InlineQueryResultArticle(id=product.product_id, title=product.product_name,
                                                                    description=u'⭐'*int(product.score)+u'  💵   '+str(product.product_price_u)+u' USD'+ self.if_discount(str(product.product_discount)),
                                                                    thumb_url=product.product_picture, input_message_content=InputTextMessageContent(u''.join(self.good_view(bot, update, product, 'Search_Inline')[0]),
                                                                    parse_mode=ParseMode.MARKDOWN), reply_markup=keyboard))

                    self.inline_list[str(update.inline_query.from_user.id)] = [1, len(results)/50]
                    self.inline_list[str(update.inline_query.from_user.id)].append(results)
                    bot.answerInlineQuery(update.inline_query.id, results[0:50], switch_pm_text=self.ut['live_here'][locale]+u'😊', next_offset='next_page')

    def pagination(self, bot, update):
        print 'pagination'
        locale = self.choosen_locale[str(update.inline_query.from_user.id)]
        current = self.inline_list[str(update.inline_query.from_user.id)][0]
        total = self.inline_list[str(update.inline_query.from_user.id)][1]
        if current >= total:
            print 'end'
            return
        results = list(self.inline_list[str(update.inline_query.from_user.id)][2][(50*current):(50*current+50)])
        bot.answerInlineQuery(update.inline_query.id, results[0:50], switch_pm_text=self.ut['live_here'][locale] + u'😊', next_offset='next_page')
        print 'next 50'
        self.inline_list[str(update.inline_query.from_user.id)][0] += 1

    def do_search(self, bot, update):
        #self.logger_wrap(update.message, 'do_search')
        if re.findall(r'[^A-Za-z0-9-\s]', update.message.text):
            local = self.choosen_locale[str(update.message.from_user.id)]
            bot.sendMessage(update.message.chat_id, text=self.ut['not_find'][local]+u'😕', parse_mode=ParseMode.MARKDOWN)
            return self.del_previous(bot, update)
        self.search_query[str(update.message.chat_id)] = update.message.text
        self.del_previous(bot, update)
        self.give(bot, update, 'Search_Down')
        self.podbor[str(update.message.chat_id)] = ['/find', str(update.message.message_id)]

    def give(self, bot, update, args):
        if update.message:
            try:
                locale = self.choosen_locale[str(update.message.from_user.id)]
            except:
                self.start(bot, update, args=None)
                return
            #self.logger_wrap(update.message, 'give')
            #telegram.ReplyKeyboardHide(hide_keyboard=True)
            id = str(update.message.message_id)
            chat_id = str(update.message.chat_id)
            self.photo_count[chat_id] = {}
            self.photo_count[chat_id][id] = 1
            self.offset[chat_id] = 1
            self.result[id] = self.product_wrap(bot, update, args)
            if self.result[id]:
                self.count[id] = 0
                if args == 'Random':
                    keyboard = self.do_keybord(0, len(self.result[id]), 'random', locale)
                    bot.sendMessage(chat_id, text=self.result[id][self.count[id]], parse_mode=ParseMode.MARKDOWN,
                                    reply_markup=keyboard)
                else:
                    keyboard = self.do_keybord(0, len(self.result[id]), 'do_picture_chat', locale)
                    bot.sendMessage(chat_id, text=self.result[id][self.count[id]], parse_mode=ParseMode.MARKDOWN, reply_markup=keyboard)
            else:
                local = self.choosen_locale[str(update.message.from_user.id)]
                bot.sendMessage(chat_id, text=self.ut['not_find'][local]+u'😕',
                                         parse_mode=ParseMode.MARKDOWN)
                self.result.__delitem__(id)
        elif update.callback_query:
            self.logger_wrap(update.callback_query.message, 'give')
            try:
                locale = self.choosen_locale[str(update.callback_query.from_user.id)]
            except:
                self.start(bot, update, args=None)
                return
            # telegram.ReplyKeyboardHide(hide_keyboard=True)
            id = str(update.callback_query.message.message_id)
            chat_id = str(update.callback_query.message.chat_id)
            self.photo_count[chat_id] = {}
            self.photo_count[chat_id][id] = 1
            self.result[id] = self.product_wrap(bot, update, args)
            if self.result[id]:
                self.count[id] = 0
                if args == 'Random':
                    self.offset[chat_id] = 0
                    keyboard = self.do_keybord(0, len(self.result[id]), 'random', locale)
                    bot.editMessageText(text=self.result[id][self.count[id]], chat_id=chat_id, message_id=id,
                                        parse_mode=ParseMode.MARKDOWN, reply_markup=keyboard)
                else:
                    keyboard = self.do_keybord(0, len(self.result[id]), 'do_picture_chat', locale)
                    bot.sendMessage(chat_id, text=self.result[id][self.count[id]], parse_mode=ParseMode.MARKDOWN,
                            reply_markup=keyboard)
            else:

                local = self.choosen_locale[str(update.callback_query.from_user.id)]
                bot.sendMessage(chat_id, text=self.ut['not_find'][local]+u'😕',
                                         parse_mode=ParseMode.MARKDOWN)
                self.result.__delitem__(id)

    def top(self, bot, update):
        self.logger_wrap(update.message, 'top')
        self.del_previous(bot, update)
        self.give(bot, update, 'TOP_Down')
        self.podbor[str(update.message.chat_id)] = ['/TOP', str(update.message.message_id)]

    def random(self, bot, update):
        if update.message:
            self.logger_wrap(update.message, 'random')
            chat_id = str(update.message.chat_id)
            self.del_previous(bot, update)
            self.give(bot, update, 'Random')
            self.podbor[chat_id] = ['/random', str(update.message.message_id)]
        elif update.callback_query:
            self.logger_wrap(update.callback_query.message, 'random')
            chat_id = str(update.callback_query.message.chat_id)
            self.del_previous(bot, update)
            self.give(bot, update, 'Random')
            self.podbor[chat_id] = ['/random', str(update.callback_query.message.message_id)]

    def do_keybord(self, current, total, flag, locale):
        if flag == 'do_picture_chat':
            keyboard = telegram.InlineKeyboardMarkup([[telegram.InlineKeyboardButton(text='<', callback_data='Previous_item'),
                                                       telegram.InlineKeyboardButton(text=str(current + 1) + self.ut['of'][locale] + str(total), callback_data='1'),
                                                       telegram.InlineKeyboardButton(text='>', callback_data='Next_item')],
                                                       [telegram.InlineKeyboardButton(text=u'📷', callback_data='Do_photo_chat'),
                                                        telegram.InlineKeyboardButton(text=u'❤', callback_data='Like')]])
        elif flag == 'picture_slide':
            keyboard = telegram.InlineKeyboardMarkup([[telegram.InlineKeyboardButton(text='<', callback_data='PreviousP'),
                                                       telegram.InlineKeyboardButton(text=str(current + 1) + self.ut['of'][locale] + str(total), callback_data='1'),
                                                       telegram.InlineKeyboardButton(text='>', callback_data='NextP'),
                                                       telegram.InlineKeyboardButton(text=u'❌', callback_data='X_c')]])

        elif flag == 'random_photo':
            keyboard = telegram.InlineKeyboardMarkup([[telegram.InlineKeyboardButton(text='<', callback_data='PreviousP_r'),
                                                       telegram.InlineKeyboardButton(text=str(current + 1) + self.ut['of'][locale] + str(total), callback_data='1'),
                                                       telegram.InlineKeyboardButton(text='>', callback_data='NextP_r'),
                                                       telegram.InlineKeyboardButton(text=u'❌', callback_data='X_r')]])
        elif flag == 'do_picture_inline':
            keyboard = telegram.InlineKeyboardMarkup([[telegram.InlineKeyboardButton(text=u'📷', callback_data='Do_photo')]])
        elif flag == 'do_picture_like':
            keyboard = telegram.InlineKeyboardMarkup([[telegram.InlineKeyboardButton(text=u'>>>❤<<<', callback_data='Favor')]])
        elif flag == 'picture_slide_inline':
            keyboard = telegram.InlineKeyboardMarkup([[telegram.InlineKeyboardButton(text='<', callback_data='PreviousP_in'),
                                                       telegram.InlineKeyboardButton(text=str(current + 1) + self.ut['of'][locale] + str(total), callback_data='1'),
                                                       telegram.InlineKeyboardButton(text='>', callback_data='NextP_in'),
                                                       telegram.InlineKeyboardButton(text=u'❌', callback_data='X_i')]])
        elif flag == 'random':
            keyboard = telegram.InlineKeyboardMarkup([[telegram.InlineKeyboardButton(text=u'🎲', callback_data='More_random'),
                                                       telegram.InlineKeyboardButton(text=u'📷', callback_data='Do_photo_random'),
                                                       telegram.InlineKeyboardButton(text=u'❤', callback_data='LikeR')]])
        return keyboard

    def inline_picture(self, bot, update):
        result = update.chosen_inline_result.result_id
        message = update.chosen_inline_result.inline_message_id
        self.user = update.chosen_inline_result.from_user
        try:
            self.inline_list.__delitem__(str(update.chosen_inline_result.from_user.id))
        except: pass
        self.query = update.chosen_inline_result.query
        k = telegram.ChosenInlineResult(result_id=result, from_user=self.user, query=self.query)
        self.answer[str(message)] = str(update.chosen_inline_result.result_id)
        try: self.photo[result]
        except: self.product_wrap(bot, update, 'ID')

    def filter_for_inline(self, bot, update):
        query = update.callback_query
        local = self.choosen_locale[str(query.from_user.id)]
        if query.data == 'More_random':
            self.random(bot, update)
        if query.data == '1':
            bot.answerCallbackQuery(callback_query_id=str(query.id),
                                    text=self.ut['other'][local][0]+u'😂')
        if query.data in ['Do_photo_chat', 'Do_photo_random']:
            self.photog(bot, update)
        if query.data == 'Next_item':
            self.get_next(bot, update)
        if query.data == 'Previous_item':
            self.get_previous(bot, update)
        if query.data == 'Close':
            self.del_previous(bot, update)
        if query.data in ['PreviousP', 'NextP', 'PreviousP_r', 'NextP_r']:
            self.slide_in_chat(bot, update)
        if query.data in ['Like', 'LikeR']:
            chat_id = str(query.message.chat_id)
            id = str(int(query.message.message_id) - self.offset[chat_id])
            #self.like[chat_id] = {'text': u'❤\n'+self.result[id][self.count[id]], 'photo': self.photo[self.podbor[chat_id][1]][self.count[self.podbor[chat_id][1]]], 'count': 0}
            if query.data == 'LikeR':
                keyboard = self.do_keybord(int(self.count[id]), len(self.result[id]), 'random', local)
            else:
                keyboard = self.do_keybord(int(self.count[id]), len(self.result[id]), 'do_picture_chat', local)
            #keyboard_in = self.do_keybord(1, 5, 'do_picture_like')
            bot.editMessageText(text=u'❤\n'+self.result[id][self.count[id]],
                                chat_id=query.message.chat_id, message_id=query.message.message_id,
                                parse_mode=ParseMode.MARKDOWN)
            bot.sendMessage(chat_id, text=self.result[id][self.count[id]], parse_mode=ParseMode.MARKDOWN,
                                reply_markup=keyboard)
            bot.answerCallbackQuery(callback_query_id=str(query.id),
                                    text=self.ut['other'][local][1]+u'😊')
            self.offset[chat_id]+=1
        if query.data in ['X_r', 'X_c']:
            chat_id = str(query.message.chat_id)
            id = str(int(query.message.message_id) - self.offset[chat_id])
            self.photo_count[chat_id][id] = 1
            if query.data == 'X_r':
                keyboard = self.do_keybord(int(self.count[id]), len(self.result[id]), 'random', local)
            else:
                keyboard = self.do_keybord(int(self.count[id]), len(self.result[id]), 'do_picture_chat', local)
            bot.editMessageText(text=self.result[id][self.count[id]],
                                chat_id=query.message.chat_id, message_id=query.message.message_id,
                                parse_mode=ParseMode.MARKDOWN, reply_markup=keyboard)
        if query.data in ['PreviousP_in', 'NextP_in']:
            self.slide_in_inline(bot, update)
        if query.data == 'Do_photo':
            id = str(self.answer[query.inline_message_id])
            self.photo_count[id] = 0
            link = self.photo[id]
            keyboard = self.do_keybord(self.photo_count[id], len(self.photo[id]), 'picture_slide_inline', local)
            bot.editMessageText(text=u'[📷](' + str(link[self.photo_count[id]]) + ')',
                                inline_message_id=query.inline_message_id,
                                parse_mode=ParseMode.MARKDOWN, reply_markup=keyboard)
            self.photo_count[id] += 1
            #bot.editMessageReplyMarkup(inline_message_id=query.inline_message_id, reply_markup=keyboard)
        if query.data == 'X_i':
            id = str(self.answer[query.inline_message_id])
            self.photo_count[id] = 0
            keyboard = self.do_keybord(1, 5, 'do_picture_inline', local)
            product = self.product_wrap(bot, update, "ID")
            bot.editMessageText(text=u''.join(product[0]),
                                inline_message_id=query.inline_message_id,
                                parse_mode=ParseMode.MARKDOWN, reply_markup=keyboard)

    def slide_in_inline(self, bot, update):
        query = update.callback_query
        local = self.choosen_locale[str(query.from_user.id)]
        id = str(self.answer[query.inline_message_id])
        if query.data == 'PreviousP_in':
            self.photo_count[id] -= 2
        #bot.sendChatAction(query.message.chat_id, action=telegram.ChatAction.TYPING)
        link = self.photo[id]
        if 0 < self.photo_count[id] + 1 <= len(link):
            keyboard = self.do_keybord(self.photo_count[id], len(link), 'picture_slide_inline', local)
            bot.editMessageText(text=u'[📷](' + str(link[self.photo_count[id]]) + ')',
                                inline_message_id=query.inline_message_id,
                                parse_mode=ParseMode.MARKDOWN, reply_markup=keyboard)
            self.photo_count[id] += 1
        else:
            self.photo_count[id] = 0
            keyboard = self.do_keybord(self.photo_count[id], len(link), 'picture_slide_inline', local)
            try:
                bot.editMessageText(text=u'[📷](' + str(link[self.photo_count[id]]) + ')',
                                    inline_message_id=query.inline_message_id,
                                    parse_mode=ParseMode.MARKDOWN, reply_markup=keyboard)
            except:
                bot.answerCallbackQuery(callback_query_id=str(query.id), text=self.ut['other'][local][2]+u'😕')
            finally:
                self.photo_count[id] += 1

    def slide_in_chat(self, bot, update):
        query = update.callback_query
        local = self.choosen_locale[str(query.from_user.id)]
        chat_id = str(query.message.chat_id)
        id = str(int(query.message.message_id)-self.offset[chat_id])
        if query.data in ['PreviousP', 'PreviousP_r']:
            self.photo_count[chat_id][id] -= 2
        link = self.photo[id][self.count[id]]
        if 0 < self.photo_count[chat_id][id] + 1 <= len(link):
            if query.data in ['PreviousP_r', 'NextP_r']:
                keyboard = self.do_keybord(self.photo_count[chat_id][id], len(link), 'random_photo', local)
            else:
                keyboard = self.do_keybord(self.photo_count[chat_id][id],len(link), 'picture_slide', local)
            bot.editMessageText(text=u'[📷]('+str(link[self.photo_count[chat_id][id]])+')',
                                chat_id=query.message.chat_id, message_id=query.message.message_id, parse_mode=ParseMode.MARKDOWN, reply_markup=keyboard)
            self.photo_count[chat_id][id] +=1
        else:
            self.photo_count[chat_id][id] = 0
            try:
                if query.data in ['PreviousP_r', 'NextP_r']:
                    keyboard = self.do_keybord(self.photo_count[chat_id][id], len(link), 'random_photo', local)
                else:
                    keyboard = self.do_keybord(self.photo_count[chat_id][id], len(link), 'picture_slide', local)
                bot.editMessageText(text=u'[📷](' + str(link[self.photo_count[chat_id][id]]) + ')',
                                    chat_id=query.message.chat_id, message_id=query.message.message_id,
                                    parse_mode=ParseMode.MARKDOWN, reply_markup=keyboard)
            except:
                bot.answerCallbackQuery(callback_query_id=str(query.id), text=self.ut['other'][local][2]+u'😕')
            finally: self.photo_count[chat_id][id] += 1

    def photog(self, bot, update):
        self.logger_wrap(update.callback_query.message, 'photo')
        query = update.callback_query
        local = self.choosen_locale[str(query.from_user.id)]
        chat_id = str(query.message.chat_id)
        id = str(int(query.message.message_id)-self.offset[chat_id])
        #bot.sendChatAction(chat_id, action=telegram.ChatAction.TYPING)
        link = self.photo[id][self.count[id]]
        if query.data == 'Do_photo_chat':
            keyboard = self.do_keybord(0, len(link), 'picture_slide', local)
        elif query.data == 'Do_photo_random':
            keyboard = self.do_keybord(0, len(link), 'random_photo', local)
        bot.editMessageText(text=u'[📷]('+str(link[0])+')',
                            chat_id=query.message.chat_id, message_id=query.message.message_id,
                            reply_markup=keyboard, parse_mode=ParseMode.MARKDOWN)

    def get_next(self, bot, update):
        self.logger_wrap(update.callback_query.message, 'next')
        query = update.callback_query
        local = self.choosen_locale[str(query.from_user.id)]
        chat_id = str(query.message.chat_id)
        id = str(int(query.message.message_id)-self.offset[chat_id])
        try:
            self.count[id] += 1
            keyboard = self.do_keybord(int(self.count[id]), len(self.result[id]), 'do_picture_chat', local)
            bot.editMessageText(text=self.result[id][self.count[id]],
                                chat_id=query.message.chat_id, message_id=query.message.message_id,
                                parse_mode=ParseMode.MARKDOWN, reply_markup=keyboard)
        except:
            self.count[id] -= 1
            bot.answerCallbackQuery(callback_query_id=str(query.id), text=self.ut['other'][local][2]+u'😕')

    def get_previous(self, bot, update):
        self.logger_wrap(update.callback_query.message, 'previous')
        query = update.callback_query
        local = self.choosen_locale[str(query.from_user.id)]
        chat_id = str(query.message.chat_id)
        id = str(int(query.message.message_id) - self.offset[chat_id])
        if self.count[id] >= 1:
            self.count[id] -= 1
            keyboard = self.do_keybord(int(self.count[id]), len(self.result[id]), 'do_picture_chat', local)
            bot.editMessageText(text=self.result[id][self.count[id]],
                                chat_id=query.message.chat_id, message_id=query.message.message_id,
                                parse_mode=ParseMode.MARKDOWN, reply_markup=keyboard)
        else:
            self.result[id] = list(self.result[id].__reversed__())
            self.photo[id] = list(self.photo[id].__reversed__())
            keyboard = self.do_keybord(int(self.count[id]), len(self.result[id]), 'do_picture_chat', local)
            bot.editMessageText(text=self.result[id][self.count[id]],
                                chat_id=query.message.chat_id, message_id=query.message.message_id,
                                parse_mode=ParseMode.MARKDOWN, reply_markup=keyboard)
            bot.answerCallbackQuery(callback_query_id=str(query.id),
                                    text=self.ut['other'][local][3]+u'⚠')

    def close(self, bot, update):
        self.logger_wrap(update.message, 'close')
        try:
            self.count[str(update.message.chat_id)] = 0
            self.result[str(update.message.chat_id)] = []
            self.search_query[str(update.message.chat_id)] = ''
            self.start(bot, update, args=None)
        except:
            self.start(bot, update, args=None)

    def unknow(self, bot, update):
        self.logger_wrap(update.message, 'unknow')

    def error(self, bot, update, error):
        self.logger_wrap(update.message, 'error')
        logger.warn('Update "%s" caused error "%s"' % (update, error))

    def idle(self):
        self.updater.start_polling()
        self.updater.idle()
示例#21
0
文件: bot.py 项目: MFarelS/ID_AzanBot
def echo(bot, update):
    chat_id = update.message.chat_id
    bot.send_message(chat_id=chat_id, text=update.message.text)

    if not 'test' in DBNAME:
        Botan(BOTAN_TOKEN).track(update.message, event_name='echo')
示例#22
0
文件: bot.py 项目: MFarelS/ID_AzanBot
def echoreply(bot, update):
    update.message.reply_text(update.message.text)

    if not 'test' in DBNAME:
        Botan(BOTAN_TOKEN).track(update.message, event_name='echoreply')
示例#23
0
            chats = db.get('chats')
            chats.remove(update.message.chat_id)
            db.set('chats', chats)
            logger.info('Removed chat_id %s from chat list'
                        % update.message.chat_id)
        else:
            logger.error("Un error (%s) ocurrió: %s"
                         % (type(error), error.message))
    except:
        pass


botan = None
if BOTAN_TOKEN != 'BOTANTOKEN':
    botan = Botan(BOTAN_TOKEN)

@run_async
def stats(bot, update, **kwargs):
    if not botan:
        return

    if botan.track(update.message):
        logger.debug("Tracking with botan.io successful")
    else:
        logger.info("Tracking with botan.io failed")


def main():
    # Create the Updater and pass it your bot's token.
    updater = Updater(TOKEN, workers=10)
示例#24
0
 def test_track(self):
     botan = Botan(self.token)
     message = MessageMock(self._chat_id)
     result = botan.track(message, 'named event')
     self.assertTrue(result)