Python telepot.Bot() Examples

The following are 16 code examples of telepot.Bot(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module telepot , or try the search function .
Example #1
Source File: telegram.py    From mcafee2cash with MIT License 6 votes vote down vote up
def __init__(self, chat_id=176900492, order_callback=lambda x: x):
		self.order_callback = order_callback
		self.bot = telepot.Bot(BOT_TOKEN)
		self.bittrex_utils = BittrexUtils()
		self.chat_id = None

		# Orders
		self.buying = None
		self.selling = None

		MessageLoop(self.bot, {
			"chat" : self.chat_handler,
			"callback_query": self.callback_query_handler
		}).run_as_thread()

		try:
			with open(".chats", "r") as f:
				self.chat_id = int(f.readlines()[0].strip())
				print(self.chat_id)
		except FileNotFoundError:
			print("No authenticated chats")
		except Exception as e:
			print(e)
		print("Running bot...") 
Example #2
Source File: alerta_telegram.py    From alerta-contrib with MIT License 6 votes vote down vote up
def __init__(self, name=None):

        self.bot = telepot.Bot(TELEGRAM_TOKEN)
        LOG.debug('Telegram: %s', self.bot.getMe())

        if TELEGRAM_WEBHOOK_URL and \
                        TELEGRAM_WEBHOOK_URL != self.bot.getWebhookInfo()['url']:
            self.bot.setWebhook(TELEGRAM_WEBHOOK_URL)
            LOG.debug('Telegram: %s', self.bot.getWebhookInfo())

        super(TelegramBot, self).__init__(name)
        if TELEGRAM_TEMPLATE:
            if os.path.exists(TELEGRAM_TEMPLATE):
                with open(TELEGRAM_TEMPLATE, 'r') as f:
                    self.template = Template(f.read())
            else:
                self.template = Template(TELEGRAM_TEMPLATE)
        else:
            self.template = Template(DEFAULT_TMPL) 
Example #3
Source File: bot.py    From django-db-mailer with GNU General Public License v2.0 6 votes vote down vote up
def send(to, message, **kwargs):
    """
       SITE: https://github.com/nickoala/telepot
       TELEGRAM API: https://core.telegram.org/bots/api

       Installation:
       pip install 'telepot>=10.4'
   """

    available_kwargs_keys = [
        'parse_mode',
        'disable_web_page_preview',
        'disable_notification',
        'reply_to_message_id',
        'reply_markup'
    ]

    available_kwargs = {
        k: v for k, v in kwargs.iteritems() if k in available_kwargs_keys
    }

    bot = telepot.Bot(settings.TELEGRAM_BOT_TOKEN)
    return bot.sendMessage(to, message, **available_kwargs) 
Example #4
Source File: send_announcement.py    From pockebot with MIT License 6 votes vote down vote up
def main(config, file_with_msg):
    with open(file_with_msg) as f:
        text_to_send = f.read()
    bot = telepot.Bot(config['telegram_token'])
    mongo = pymongo.MongoClient(host=config['mongo']['host'])
    people = mongo[config['mongo']['db']]['people']
    already_sent = mongo[config['mongo']['db']]['people_sent']
    cursor = people.find({})
    count = 0
    for record in cursor:
        print('>> {}'.format(count))
        print(record)
        if already_sent.find_one({'id': record['id']}) is None:
            already_sent.insert_one({'id': record['id']})
            send(bot, record['id'], text_to_send)
        count += 1 
Example #5
Source File: main_app.py    From pockebot with MIT License 6 votes vote down vote up
def __init__(self, seed_tuple, timeout, is_main=True, config=None):
        super(PocketBot, self).__init__(seed_tuple, timeout)
        self.visit_time = 0
        self.find_url = re.compile('(https?://[^\s]+)')
        self.find_tag = re.compile("#[\w']+")
        self.mongo = db.PockebotDBSlave(config)
        self.is_main = is_main
        self.messages = list()
        self.pocket_client = pocket.PocketbotPocketSlave(config['pocket_token'])
        # For forwarding /feedback messages
        self.stuff_bot = telepot.Bot(config['support_bot_token'])
        self.dev_group_chat = config['developers_group']
        # User state
        self.lang = 'en'
        self.tags_promt = True
        self.set_pockebot_tag = True
        self.session_cnt = 0
        self.audio = False
        self.request_chat_id = None
        self._edit_msg_ident = None
        self._editor = None
        self.waiting_for_menu_action = False
        self.reading_time_tag = True 
Example #6
Source File: eclipse.py    From BrainDamage with Apache License 2.0 6 votes vote down vote up
def main():

    global bot
    
    startupThread = threading.Thread(target=startUpWork, args=())
    startupThread.daemon = True
    startupThread.start()
    
    if internetOn():
        try:
            bot = telepot.Bot(access_token)
            bot.message_loop(handle)
            bot.sendMessage(CHAT_ID, str(current_system_time.strftime("%d|%m|%Y-%H|%M|%S")) + ': '+ USER + ' is online ^_^')
            print ('[*] Listening ...')
            try:
                while 1:
                    time.sleep(5)
            except KeyboardInterrupt:
                print '[*] Eclipse completed...'
        except Exception as e:
            pass 
Example #7
Source File: artlas.py    From ARTLAS with MIT License 5 votes vote down vote up
def __init__(self, config_file):

		print('[*] Getting config...')
		self.conf = dict()
		self.get_conf(config_file)
		print('[+] Done!\n')

		# Check if CEF_Syslog is enabled
		if self.conf['cef_syslog_enable']:
			print '[+] Syslog Enabled'
			self.syslog = syslog.Syslog(self.conf['cef_syslog_server'])

		# Check if Telegram is enabled
		if self.conf['telegram_enable']:
			print '[+] Telegram Enabled'
			self.bot = telepot.Bot(self.conf['api'])

		# Check if Zabbix is enabled
		if self.conf['zabbix_enable']:
			print '[+] Zabbix Enabled'
			print 'Notifications ',self.conf['notifications']
			print 'Advanced ',self.conf['zabbix_advantage_keys']
		print 

		print('[*] Getting rules...')
		self.get_file_rules()
		print('[+] Done!\n')

		self.rules = json.loads(open(self.conf['rules']).read())

		# List of all senders, enabled or not
		self.senders = [self.send_zabbix, self.send_cef_syslog, self.send_telegram]


		print('[*] A.R.T.L.A.S Started!\n') 
Example #8
Source File: _tg_tqdm.py    From tg_tqdm with MIT License 5 votes vote down vote up
def __init__(self, token, chat_id, show_last_update=True):
        self.bot = telepot.Bot(token)
        self.chat_id = chat_id
        self.text = self.prev_text = '<< Init tg_tqdm bar >>'
        self.message_id = self.bot.sendMessage(chat_id, self.text)['message_id']
        self.show_last_update = show_last_update 
Example #9
Source File: paw_app.py    From google-search-telegram-bot with Apache License 2.0 5 votes vote down vote up
def __init__(self):
		Log.i("Initializing PAW app")
		self._init_paw_telepot()
		self._bot = telepot.Bot(self.TELEGRAM_TOKEN) 
Example #10
Source File: standalone_app.py    From google-search-telegram-bot with Apache License 2.0 5 votes vote down vote up
def __init__(self):
		Log.i("Initializing standalone app")
		self._bot = telepot.Bot(self.TELEGRAM_TOKEN)
		self._answerer = telepot.helper.Answerer(self._bot) 
Example #11
Source File: telebot.py    From PGO-mapscan-opt with GNU General Public License v3.0 5 votes vote down vote up
def do_settings():
    global radius_by_default,radius_step,radius_max,messages, POKEMONS, POKEMON_NUM,about,bot,log_queue,log_to_file,ignored_default,log_notifications,max_notis_per_user_and_cycle,time_between_cycles
    with open('{}/res/telebotsettings.json'.format(workdir)) as f:
        telecfg = json.load(f)

    language = telecfg["language"]
    radius_by_default = int(telecfg["radius_by_default"])
    radius_step = telecfg["radius_step"]
    radius_max = telecfg["radius_max"]
    max_notis_per_user_and_cycle = telecfg["max_notis_per_user_and_cycle"]
    time_between_cycles = telecfg["time_between_cycles"]
    log_notifications = telecfg["log_notifications"]

    log_to_file = telecfg["log_to_file"]

    bot = telepot.Bot(str(telecfg["TELEGRAM_BOT_TOKEN"]))
    about = telecfg["info_about"]

    ignored_default = telecfg["ignored_by_default"]
    if type(ignored_default) == unicode:
        print(time.strftime('[%H:%M:%S] ' + '[!] Warning, the ignored_by_default setting in telebotsettings.json should be now a array like [1,2,3] instead of a string like "1,2,3"'))
        sys.exit()

    with open('{}/res/languages/{}.json'.format(workdir, language)) as f:
        messages = json.load(f)

    with open('{}/webres/static/{}.json'.format(workdir, language)) as f:
        POKEMONS = json.load(f) 
Example #12
Source File: telebot.py    From PGO-mapscan-opt with GNU General Public License v3.0 5 votes vote down vote up
def send_message(chat_id, text, disable_notification=False, reply_markup=None, disable_web_page_preview=False):
    try:
        if reply_markup is None:
            bot.sendMessage(chat_id, text, parse_mode='HTML', disable_notification=disable_notification, disable_web_page_preview=disable_web_page_preview)
        else:
            bot.sendMessage(chat_id, text, parse_mode='HTML', disable_notification=disable_notification, disable_web_page_preview=disable_web_page_preview, reply_markup=reply_markup)
    except BotWasBlockedError:
        print_log("[!] Bot was blocked. Couldn't send message.")
    except TelegramError as e:
        print_log("[!] An error happened while sending message " + str(e.json))
    except Exception as e:
        print_log("[!] An unkown error happened while sending message, error: {}".format(e)) 
Example #13
Source File: telegram_bot_client.py    From cakechat with Apache License 2.0 5 votes vote down vote up
def __init__(self, token):
        """

        :param token: a bot authorization token, can be obtained from the @BotFather bot.
        """
        super(TelegramBot, self).__init__()

        self._token = token
        self._bot = telepot.Bot(token)
        self._chat_id_to_session = {} 
Example #14
Source File: __init__.py    From reddit2telegram with MIT License 5 votes vote down vote up
def __init__(self, t_channel=None, config=None):
        super(Reddit2TelegramSender, self).__init__()
        if config is None:
            with open('configs/prod.yml') as f:
                config = yaml.load(f.read())
        self.config = config
        self.telepot_bot = telepot.Bot(self.config['telegram']['token'])
        if t_channel is None:
            t_channel = '@r_channels_test'
        self.t_channel = t_channel
        self._make_mongo_connections()
        time.sleep(2) 
Example #15
Source File: admin.py    From spntaBot with GNU General Public License v3.0 5 votes vote down vote up
def run(message, matches, chat_id, step):
    if matches == 'add':
        if r.sismember('groups', chat_id):
            bot.sendMessage(chat_id, ln['admin']['add']["0"])
        else:
            r.sadd('groups', chat_id)
            bot.sendMessage(chat_id, ln['admin']['add']["1"])
    elif matches == 'rem':
        if r.sismember('groups', chat_id):
            r.srem('groups', chat_id)
            bot.sendMessage(chat_id, ln['admin']['rem']['0'])
        else:
            bot.sendMessage(chat_id, ln['admin']['rem']['1'])
    elif matches == 'leave':
        bot.leaveChat(chat_id)
    elif matches == 'stats':
        mmd = ['photo', 'video', 'voice', 'video_note', 'contact', 'sticker',
               'audio', 'text', 'location', 'document', 'new_chat_member']
        text = 'Stats Bot:'
        i = 0
        for x in mmd:
            get = r.get('msg:{}'.format(x))
            text += '\n>{} : {}'.format(x, get)
            i = i + int(get)
        text += '\n>All Message : {}'.format(i)
        text += '\n>pv members: {}'.format(r.scard('spntapv'))
        text += '\n>Groups: {}'.format(r.scard('groups'))
        bot.sendMessage(chat_id, text)
    elif matches == 'fbc':
        if 'reply_to_message' in message:
            m = message['reply_to_message']
            gp = r.smembers('groups')
            i = 0
            for x in gp:
                try:
                    send = bot.forwardMessage(x, m['chat']['id'], m['message_id'])
                    if send:
                        i += 1
                except:
                    pass
            bot.sendMessage(chat_id, 'به {} گروه ارسال شد'.format(i)) 
Example #16
Source File: skeleton_route.py    From telepot with MIT License 5 votes vote down vote up
def on_inline_query(msg):
    def compute():
        query_id, from_id, query_string = telepot.glance(msg, flavor='inline_query')
        print('%s: Computing for: %s' % (threading.current_thread().name, query_string))

        articles = [InlineQueryResultArticle(
                        id='abcde', title='Telegram', input_message_content=InputTextMessageContent(message_text='Telegram is a messaging app')),
                    dict(type='article',
                        id='fghij', title='Google', input_message_content=dict(message_text='Google is a search engine'))]

        photo1_url = 'https://core.telegram.org/file/811140934/1/tbDSLHSaijc/fdcc7b6d5fb3354adf'
        photo2_url = 'https://www.telegram.org/img/t_logo.png'
        photos = [InlineQueryResultPhoto(
                      id='12345', photo_url=photo1_url, thumb_url=photo1_url),
                  dict(type='photo',
                      id='67890', photo_url=photo2_url, thumb_url=photo2_url)]

        result_type = query_string[-1:].lower()

        if result_type == 'a':
            return articles
        elif result_type == 'p':
            return photos
        else:
            results = articles if random.randint(0,1) else photos
            if result_type == 'b':
                return dict(results=results, switch_pm_text='Back to Bot', switch_pm_parameter='Optional_start_parameter')
            else:
                return dict(results=results)

    answerer.answer(msg, compute)