def start_multimon(freq, prot, minlen, tid, rid): # replace POCSAG512 with -a POCSAG512 prot = prot.replace(" ", " -a ") # create telegram bot bot = Bot(tid) # create deque d = collections.deque(maxlen=100) # call multimon call = "rtl_fm -d0 -f " + freq + " -s 22050 | multimon-ng -t raw -a " + prot + " -f alpha -t raw /dev/stdin -" print(call) mm = subprocess.Popen(call, shell=True, stdout=subprocess.PIPE) while mm.poll() is None: # process new pocsag entry output = mm.stdout.readline().decode('utf-8') # read new line print(output) if "Alpha" not in output: # check if non alpha element continue # if yes, continue output = output.replace("<NUL>", "") # replace terminator sequence if output in d: # if the message is already in the list -> skip (pager messages might be sent multiple times) continue d.append(output) # add to deque msg = output.split("Alpha:", 1)[1] # get the message if int(len(msg)) < int(minlen): # if msg length < minlen skip continue time = strftime("%Y-%m-%d %H:%M", gmtime()) # get timestamp print(msg) # print the message try: bot.send_message(rid, 'Time: ' + time + '\nMessage: ' + msg) # send it. except: pass
def proxy_telegram(api_key, https=False, host="localhost", hookpath="/income/{API_KEY}", full_url=None): logger.debug( "https: {!r}, host: {!r}, hookpath: {!r}, full_url: {!r}".format( https, host, hookpath, full_url)) if full_url is None: full_url = "http" + ("s" if https else "") + "://" + host + hookpath.format( API_KEY=api_key) # end if bot = Bot(api_key, return_python_objects=False) if bot.get_webhook_info()["result"]["url"] == "": logger.info("Webhook unset correctly. No need to change.") else: logger.debug(bot.delete_webhook()) # end def last_update = 0 while True: result = bot.get_updates(offset=last_update, poll_timeout=1000) updates = result["result"] n = len(updates) for i, update in enumerate(updates): last_update = update['update_id'] + 1 logger.debug( "Polling update ({i:03}/{n:03}|{l}):\n{u}\n{r!r}".format( r=update, i=i, n=n, l=last_update, u=full_url)) requests.post(full_url, json=update, headers={ 'Content-Type': 'application/json', 'Cache-Control': 'no-cache' })
def __init__(self, API_KEY, debug=False): if API_KEY is None: API_KEY = self.ask_for_apikey() self._api_key = API_KEY self.bot = Bot(API_KEY, return_python_objects=True) self.me = self.bot.get_me() logger.info("Information about myself: {info}".format(info=self.me)) self.METHOD_INCLUDES.update({ "debug": self.cmd_debug, "help": self.cmd_help, }) self.color = Color() self.update_thread = self.create_update_thread() self.functions = {k: v for k, v in self.get_functions()} self.current_candidates = [] self.is_debug = debug self.query = "pytgbot> " # in front of the input. self.register_tab_completion()
def main(): # get you bot instance. bot = Bot(API_KEY, return_python_objects=False) # Set `return_python_objects=False` # because we need to be really fast to answer inline queries in time, # and my computer is crap, # so any nanosecond this adds is too much, # resulting in the queries timing out. logging.add_colored_handler(logger_name=__name__, level=logging.DEBUG) my_info = bot.get_me() logger.info("Information about myself: {info}".format(info=my_info)) last_update_id = 0 mlfw = MLFW(bot) while True: # loop forever. for update in bot.get_updates(limit=100, offset=last_update_id+1, error_as_empty=True).result: last_update_id = update.update_id logger.debug(update) if "inline_query" not in update or not update.inline_query: continue inline_query_id = update.inline_query.id query = update.inline_query.query query_offset = update.inline_query.offset mlfw.search(query, inline_query_id, offset=query_offset)
def __init__(self, config: Config): """Create a bot using the config. Required keys: bot.key, bot.running, bot.chat_id, bot.offset""" self.config = config self.running = config['bot'].getboolean('running', True) self._bot = Bot(config['bot'].get('key')) self._chat_id = config['bot'].getint('chat_id', 0) self.consume_messages()
def main(): logging.add_colored_handler(level=logging.DEBUG) # get you bot instance. bot = Bot(API_KEY, return_python_objects=True) print(bot.get_me()) # do the update loop. last_update_id = 0 while True: # loop forever. updates = bot.get_updates(limit=100, offset=last_update_id + 1) for update in updates: # for every new update last_update_id = update.update_id print(update) result = update.to_array() assert isinstance(result, dict) print(result)
def init_bot(self): """ Creates the bot, and retrieves information about the bot itself (username, user_id) from telegram. :return: """ if not self._bot: # so you can manually set it before calling `init_app(...)`, # e.g. a mocking bot class for unit tests self._bot = Bot(self._api_key, return_python_objects=self._return_python_objects) elif self._bot.return_python_objects != self._return_python_objects: # we don't have the same setting as the given one raise ValueError("The already set bot has return_python_objects {given}, but we have {our}".format( given=self._bot.return_python_objects, our=self._return_python_objects )) # end def myself = self._bot.get_me() if self._bot.return_python_objects: self._user_id = myself.id self._username = myself.username else: self._user_id = myself["result"]["id"] self._username = myself["result"]["username"]
def main(API_KEY): if API_KEY is None: API_KEY = answer("Input API key") # get your bot instance. bot = Bot(API_KEY, return_python_objects=True) my_info = bot.get_me() print("Information about myself: {info}".format(info=my_info)) in_tread = Thread(target=get_updates, name="cli input thread", args=(bot, )) in_tread.daemon = True in_tread.start() notice = "You can enter commands now.\n" while True: cmd = input(notice) notice = "" # never display again. try: result_str = parse_input(bot, cmd) if result_str: print(result_str) except Exception as e: logger.exception("Error.") print("Error: " + str(e))
def setUp(self) -> None: self.api_bot = Bot(TEST_BOT_AUTH) self.user_bot = Bot(TEST_USER_AUTH)
from pytgbot.api_types.receivable.inline import InlineQuery from pytgbot.api_types.receivable.updates import Update from pytgbot.exceptions import TgApiException __author__ = 'luckydonald' import logging logger = logging.getLogger(__name__) from somewhere import API_KEY # so I don't upload them to github :D # Just remove the line, and add API_KEY="..." from pytgbot import Bot from luckydonaldUtils.encoding import to_native as n # get you bot instance. bot = Bot(API_KEY) my_info = bot.get_me() print("Information about myself: {info}".format(info=my_info)) last_update_id = 0 while True: # loop forever. for update in bot.get_updates(limit=100, offset=last_update_id + 1, error_as_empty=True): assert isinstance(update, Update) last_update_id = update.update_id print(update) if not update.inline_query: continue query_obj = update.inline_query
from pytgbot.api_types.receivable.updates import Message from pytgbot.api_types.sendable.reply_markup import InlineKeyboardButton, InlineKeyboardMarkup from pytgbot.exceptions import TgApiException import logging __author__ = 'luckydonald' logger = logging.getLogger(__name__) from somewhere import API_KEY # just set the key manually. # API_KEY = "1231412:adLsIfTsTsLfEfPdIdPwdwIoSaBgEuSzTwszPdOaNdYs" photo_cache = {} # stores the images. # get a bot instance bot = Bot(API_KEY, return_python_objects=True) def main(): last_update_id = -1 while True: # loop forever. try: updates = bot.get_updates(limit=100, offset=last_update_id + 1, poll_timeout=30, error_as_empty=True) for update in updates: last_update_id = update.update_id if not (update.message and "/start"
elif context['intent'] == 'roolback' and 'type' in context['parameters']: if context['parameters']['type'] == 'frontend': bot.send_message(user_id, get_doing_fallback('roolback', 'frontend')) SemacFrontend(bot, user_id).revert() elif context['parameters']['type'] == 'backend': bot.send_message(user_id, get_doing_fallback('roolback', 'backend')) SemacBackend(bot, user_id).revert() elif context['intent'] == 'view' and 'type' in context['parameters']: if context['parameters']['type'] == 'frontend': SemacFrontend(bot, user_id).show_actual_version() elif context['parameters']['type'] == 'backend': SemacBackend(bot, user_id).show_actual_version() else: bot.send_message(user_id, get_default_fallback()) # Setup bot bot = Bot(BOT_TOKEN) # Sending a message when bot is on bot.send_message(ALLOWED_IDS[0], "Estou online de novo!") # Get last message sended last_update_id = 0 while True: for update in bot.get_updates(limit=100, offset=last_update_id+1): last_update_id = update.update_id process_input(update.to_array())
from secrets import API_KEY, HOSTNAME, URL_PATH from api import MLFW from sentry import add_error_reporting __author__ = 'luckydonald' logger = logging.getLogger(__name__) VERSION = "1.3.1" __version__ = VERSION app = Flask(__name__) app.register_blueprint(version_bp) sentry = add_error_reporting(app) bot = Bot(API_KEY, return_python_objects=False) # Set `return_python_objects=False` # because we need to be really fast to answer inline queries in time, # and my computer is crap, # so any nanosecond this adds is too much, # resulting in the queries timing out. username = bot.get_me().result.username logging.add_colored_handler(level=logging.DEBUG) mlfw = MLFW(bot) def to_json_remove_api_key(func): """ Jsonfify returned stuff, if dict or list
def test_send_sticker(self): original_file_id = 'CAACAgIAAx0EUh03EAADDl-oWPT0MOIQZ93aktaAu8hU8rPEAAK2BgACAoujAAFGAUWZ6DSbtR4E' try: from pytgbot import Bot except ImportError: return self.fail('pytgbot dependency missing') # end try if not API_KEY: return self.fail('API_KEY not set') # end if if not CHAT_ID: return self.fail('CHAT_ID not set') # end if bot = Bot(API_KEY) msg = bot.send_sticker(chat_id=CHAT_ID, sticker=original_file_id) print(msg) sticker_file = FileId.from_file_id(msg.sticker.file_id) sticker_file_unique_id = FileUniqueId.from_file_id( msg.sticker.file_id).to_unique_id() self.assertEqual(msg.sticker.file_unique_id, sticker_file_unique_id) self.assertEqual(FileId.TYPE_STICKER, sticker_file.type_id) self.assertEqual('sticker', sticker_file.type_detailed) self.assertEqual('document', sticker_file.type_generic) self.assertEqual(sticker_file.version, FileId.MAX_VERSION[0], 'sticker should be supported max (sub_)version') self.assertEqual(sticker_file.sub_version, FileId.MAX_VERSION[1], 'sticker should be supported max (sub_)version') self.assertEqual(46033261910034102, sticker_file.id) self.assertEqual(-5360632757845950138, sticker_file.access_hash) self.assertEqual(2, sticker_file.dc_id) # self.assertEqual(b64decode('BFIdNxAAAAAOX6hY9PQw4hBn3dqS1oC7yFTys8Q='), sticker_file.file_reference) thumb_file = FileId.from_file_id(msg.sticker.thumb.file_id) # 'AAMCAgADGQMAAQHUiF-oKLkvxChbEROPTTw6Aagft9bPAAK2BgACAoujAAFGAUWZ6DSbtUufgioABAEAB20AAwpQAAIeBA' thumb_file_unique_id = FileUniqueId.from_file_id( thumb_file).to_unique_id() self.assertEqual(msg.sticker.thumb.file_unique_id, thumb_file_unique_id) self.assertEqual(FileId.TYPE_THUMBNAIL, thumb_file.type_id) self.assertEqual('thumbnail', thumb_file.type_detailed) self.assertEqual('photo', thumb_file.type_generic) self.assertEqual(sticker_file.version, thumb_file.version) self.assertEqual(sticker_file.sub_version, thumb_file.sub_version) self.assertEqual(sticker_file.id, thumb_file.id) self.assertEqual(sticker_file.access_hash, thumb_file.access_hash) self.assertEqual(sticker_file.dc_id, thumb_file.dc_id) self.assertEqual(sticker_file.file_reference, thumb_file.file_reference) # PhotosizeSource self.assertIsInstance(thumb_file.photosize, PhotoFileId.PhotosizeSource) self.assertEqual(20490, thumb_file.photosize.location_local_id) self.assertEqual(713203531, thumb_file.photosize.volume_id) self.assertEqual(PhotoFileId.PHOTOSIZE_SOURCE_THUMBNAIL, thumb_file.photosize.type_id) # PhotosizeSourceThumbnail self.assertIsInstance(thumb_file.photosize, PhotoFileId.PhotosizeSourceThumbnail) self.assertEqual(b'm', thumb_file.photosize.thumbnail_type) self.assertEqual(FileId.TYPE_THUMBNAIL, thumb_file.photosize.file_type)
def test_get_chat_picture_supergroup(self): try: from pytgbot import Bot except ImportError: return self.fail('pytgbot dependency missing') # end try if not API_KEY: return self.fail('API_KEY not set') # end if if not SUPERGROUP_ID: return self.fail('SUPERGROUP_ID not set') # end if bot = Bot(API_KEY) chat = bot.get_chat(chat_id=SUPERGROUP_ID) print(repr(chat)) if not chat.photo: return self.skipTest('Test chat has no picture') # end if # big picture big_file = FileId.from_file_id( chat.photo.big_file_id ) # 'AQADAgATqfDdly4AAwMAA4siCOX_____AAhKowIAAR4E' big_file_unique_id = FileUniqueId.from_file_id( chat.photo.big_file_id).to_unique_id() self.assertEqual(chat.photo.big_file_unique_id, big_file_unique_id) self.assertEqual(FileId.TYPE_PROFILE_PHOTO, big_file.type_id) self.assertEqual('profile picture', big_file.type_detailed) self.assertEqual('photo', big_file.type_generic) self.assertEqual(big_file.version, FileId.MAX_VERSION[0], 'sticker should be supported max (sub_)version') self.assertEqual(big_file.sub_version, FileId.MAX_VERSION[1], 'sticker should be supported max (sub_)version') self.assertEqual(0, big_file.id) self.assertEqual(0, big_file.access_hash) self.assertEqual(False, big_file.has_reference) self.assertEqual(False, big_file.has_web_location) self.assertIsInstance(big_file.photosize, PhotoFileId.PhotosizeSource) # self.assertEqual(200116400297, big_file.photosize.volume_id) # self.assertEqual(172874, big_file.photosize.location_local_id) self.assertEqual(PhotoFileId.PHOTOSIZE_SOURCE_DIALOGPHOTO_BIG, big_file.photosize.type_id) self.assertIsInstance(big_file.photosize, PhotoFileId.PhotosizeSourceDialogPhotoBig) self.assertEqual(SUPERGROUP_ID, big_file.photosize.dialog_id) self.assertNotEqual(0, big_file.photosize.dialog_access_hash) # small picture small_file = FileId.from_file_id( chat.photo.small_file_id ) # 'AQADAgATqfDdly4AAwIAA4siCOX_____AAhIowIAAR4E' small_file_unique_id = FileUniqueId.from_file_id( chat.photo.small_file_id).to_unique_id() self.assertEqual(chat.photo.small_file_unique_id, small_file_unique_id) self.assertEqual(FileId.TYPE_PROFILE_PHOTO, small_file.type_id) self.assertEqual(big_file.type_detailed, small_file.type_detailed) self.assertEqual(big_file.type_generic, small_file.type_generic) self.assertEqual(big_file.version, small_file.version) self.assertEqual(big_file.sub_version, small_file.sub_version) self.assertEqual(big_file.id, small_file.id) self.assertEqual(big_file.access_hash, small_file.access_hash) self.assertEqual(big_file.has_reference, small_file.has_reference) self.assertEqual(big_file.has_web_location, small_file.has_web_location) self.assertIsInstance(small_file.photosize, PhotoFileId.PhotosizeSource) self.assertEqual(big_file.photosize.volume_id, small_file.photosize.volume_id) # self.assertEqual(172872, small_file.photosize.location_local_id) self.assertEqual(PhotoFileId.PHOTOSIZE_SOURCE_DIALOGPHOTO_SMALL, small_file.photosize.type_id) self.assertIsInstance(small_file.photosize, PhotoFileId.PhotosizeSourceDialogPhotoSmall) self.assertEqual(SUPERGROUP_ID, small_file.photosize.dialog_id) self.assertEqual(big_file.photosize.dialog_access_hash, small_file.photosize.dialog_access_hash)