def test_it_replies_a_message(self): bot = TelegramBot(token='123') bot.reply_message(self.message, 'message') self.bot.send_message.assert_called_once_with(self.message.chat_id, 'message')
def index(): req = request.get_json() bot = TelegramBot() bot.parse_webhook_data(req) success = bot.action() return jsonify(success=success ) # TODO: Success should reflect the success of the reply
def index(): req = request.get_json() print(json.dumps(req)) bot = TelegramBot() bot.parse_webhook_data(req) success = bot.action() return jsonify(success=success) # TODO: Success should reflect the success of the reply it is important else it will continue to send up message
def main(): # load config with open('config.yaml') as fd: config = yaml.load(fd, Loader=yaml.FullLoader) # login client = TGTGClient(config['email'], config['password']) client._login() # setup telegram bot if config['telegram_chat_id'] is not None and config[ 'telegram_api_token'] is not None: bot = TelegramBot(config['telegram_chat_id'], config['telegram_api_token']) else: bot = None print('No Telegram configuration given, will not send messages.') # check for news while True: for item_id in config['item_list']: item = client.get_item(str(item_id)) if item['items_available'] > 0: msg = format_message(item) print(msg) if bot is not None: bot.announce(msg) time.sleep(random.random()) print(f'--- waiting {config["interval"]}s ---') time.sleep(config['interval']) # this will drift
def _send_telegram(self): """ send one telegram message per news. :return: """ bot = TelegramBot() for i in range(0, len(self.matching_articles)): current = self.matching_articles[i] label = current.get('label').get('name') articles = current.get('articles') for article in articles: try: msg = "\n" \ "*New News Item for* {}: \n" \ "*Title*: {} \n" \ "*Tags*: {} \n" \ "*Source*: {} \n" \ "*URL*: {} \n".format(label, article.get('title'), article.get('tags'), article.get('source'), article.get('link')) except UnicodeEncodeError as e: msg = "\n" \ "*New News Item for* {}: \n" \ "*Title*: {} \n" \ "*Tags*: {} \n" \ "*Source*: {} \n".format(label, article.get('title'), article.get('tags'), article.get('source')) bot.send_message(msg)
def test_it_registers_a_command(self): def a_command(request: CommandRequest): pass bot = TelegramBot(token='123') bot.register_command('cmd', a_command) self.expect_command_handler_is_registered('cmd')
def main(): agency = Agency() agency.run([MAIN_AGENT_TOKEN]) # all the main obj that last for all the time that the bot run must be created on this level telegram_starter = Starter(telegram_bot_abstraction) telegram_bot = TelegramBot(TELEGRAM_TOKEN, telegram_starter) telegram_bot.run()
def index(): req = request.get_json() if "message" in req: bot = TelegramBot() response = bot.prepare_response(req) bot.send_message(response) else: response = {} return response
def test_it_starts_telegram_bot(self): bot = TelegramBot(token='123') bot.start() self.Updater.assert_called_once_with(token='123', use_context=True) self.Bot.assert_called_once_with(token='123') self.updater.start_polling.assert_called_once() self.expect_command_handler_is_registered('start')
def test_command_request_message(self): update = Update(update_id=0, message=self.message) context = CallbackContext(self.dispatcher) bot = TelegramBot(token='123') def a_command(request: CommandRequest): assert request.message is update.message bot.register_command('command', a_command) self.inject_command('command', update, context)
def test_it_runs_command(self): command_callback = MagicMock() def a_command(request: CommandRequest): command_callback() bot = TelegramBot(token='123') bot.register_command('command', a_command) self.inject_dummy_command('command') command_callback.assert_called_once()
def find_and_notify(): notified_games = Notified() informers: List[GameInformer] = [EpicGamesStore()] tb = TelegramBot(TELEGRAM_API_KEY, TELEGRAM_CHAT_ID) free_games: List[GameData] = [] for informer in informers: free_games.extend(informer.get_free_games()) for free_game in free_games: if not notified_games.has(free_game): print('Free not notified game: ', free_game) tb.notify(free_game) notified_games.add(free_game)
def main(): TelegramBot.with_token(TELEGRAM_BOT_TOKEN) \ .add_command_handler("start", handle_start) \ .add_command_handler("takephoto", handle_take_photo) \ .add_command_handler("recordvideo", handle_record_video) \ .add_command_handler("feed", handle_feed) \ .add_command_handler("forwardservo", handle_forward_servo) \ .add_command_handler("backwardservo", handle_backward_servo) \ .add_command_handler("resetservo", handle_reset_servo) \ .add_command_handler("viewlog", handle_view_log) \ .add_default_message_handler(handle_default_message) \ .add_error_handler(handle_error) \ .start()
def index(): req = request.get_json() bot = TelegramBot() bot.parse_webhook_data(req) if bot.incoming_message_text == '/start': message = 'Enter search in format /search "train number"' success=bot.send_msg(bot.chat_id,message) return jsonify(success=success) elif bot.incoming_message_text[0:7]=="/search": if bot.incoming_message_text[8:].strip(" ")==False: success=bot.send_msg(bot.chat_id,"please enter some text") return jsonify(success=success) searching_text=bot.incoming_message_text[8:] print(searching_text) message="" response=requests.get(f"https://www.etrainstatus.com/live-status?train_number={searching_text}") soup=bs4.BeautifulSoup(response.content, 'lxml') result=soup.find(class_='contantprt') for li in result.findAll('li'): message=message+'\n'+li.text #response=requests.get(f"https://api.sumanjay.cf/torrent/?query={searching_text}") #for x in response.json()[0:3]: #message+=f"'name' : {x['name']} \n age:{x['age']} \n 'magnet' : {x['magnet']} \n\n " print(str(message)) success=bot.send_msg(bot.chat_id,urllib.parse.quote(message)) return jsonify(success=success) else: message = "invalid command" success=bot.send_msg(bot.chat_id,"Invalid Command") return jsonify(success=success)
def index(): req = request.get_json() bot = TelegramBot() bot.parse_webhook_data(req) if bot.incoming_message_text == '/start': message = '🤙Enter search in format /search "text"🤙' success=bot.send_msg(bot.chat_id,message) return jsonify(success=success) elif bot.incoming_message_text[0:7]=="/search": if bot.incoming_message_text[8:].strip(" ")==False: success=bot.send_msg(bot.chat_id,"please enter some text") return jsonify(success=success) searching_text=bot.incoming_message_text[8:] print(searching_text) message="" response=requests.get(f"https://api.sumanjay.cf/torrent/?query={searching_text}") for x in response.json()[0:3]: message+=f"'name' : {x['name']} \n age:{x['age']} \n 'magnet' : {x['magnet']} \n\n " print(str(message)) success=bot.send_msg(bot.chat_id,urllib.parse.quote(message)) return jsonify(success=success) else: message = "invalid command" success=bot.send_msg(bot.chat_id,"Invalid Command") return jsonify(success=success)
def test_it_declares_a_function_as_a_bot_command(self): bot = TelegramBot(token='123') @bot.command('command') def a_command(request: CommandRequest): pass self.expect_command_handler_is_registered('command')
def __init__(self): self.PrintHelp() self.notibot = TelegramBot() with open('private.txt', 'r') as f: data = f.read() data = data.split('\n') for i in data: if 'accesskey' in i: self.access_key = i[i.find(':') + 1:] elif 'privatekey' in i: self.private_key = i[i.find(':') + 1:] elif 'telegramtoken' in i: token = i[i.find(':') + 1:] elif 'telegramchatid' in i: chatid = i[i.find(':') + 1:] self.notibot.SetToken(token) self.notibot.SetChatId(chatid)
def main(): config = configparser.ConfigParser() config.read(os.path.join(os.path.dirname(__file__), 'config.ini')) bot = TelegramBot(config['global']['telegram_api'], config['global']['telegram_master'], config['global']['zmq_port']) TelegramThread(bot).start() while True: time.sleep(1)
def __init__(self, settings: Settings = None): self.settings = settings opts = ChromeOptions() if USER_DATA_DIR: opts.add_argument('user-data-dir=' + USER_DATA_DIR) opts.add_experimental_option("prefs", { "download.default_directory": DEFAULT_DOWNLOAD_DIRECTORY, "download.prompt_for_download": False, "download.directory_upgrade": True, "safebrowsing_for_trusted_sources_enabled": False, "safebrowsing.enabled": False }) self.driver = Chrome(executable_path=os.getcwd() + '/chromedriver.exe', options=opts) self.chat_messages = dict() self.telegram_bot = TelegramBot()
def start_forwarding(): from telegram_bot import TelegramBot, TelegramBotConfig from coolq_bot import CoolQBot, CoolQBotConfig cloud_instance = Cloud() coolq_bot_config = CoolQBotConfig(API_ROOT, SECRET, ACCESS_TOKEN) coolq_bot = CoolQBot(cloud_instance, MESSAGE_TARGET_COOLQ, coolq_bot_config) friend_map, group_map = coolq_bot.get_contact_map() telegram_bot_friend_config = TelegramBotConfig(FRIEND_TOKEN, PROXY_URL) TelegramBot(cloud_instance, MESSAGE_TARGET_TELEGRAM_FRIEND, telegram_bot_friend_config, friend_map) telegram_bot_group_config = TelegramBotConfig(GROUP_TOKEN, PROXY_URL) TelegramBot(cloud_instance, MESSAGE_TARGET_TELEGRAM_GROUP, telegram_bot_group_config, group_map)
def main(): """ Start Top Logger notifier. Make sure you've set all necessary settings in config.py """ top_logger = TopLogger() queue = config.QUEUE # setup telegram telegram_bot = TelegramBot(config.TOKEN) telegram_bot.set_queue(queue) # start schedule init_notification(telegram_bot, queue) try: repeat(top_logger, telegram_bot, queue, config.INTERVAL) except KeyboardInterrupt: exit_notification(telegram_bot) sys.exit(0)
def check(top_logger: TopLogger, telegram: TelegramBot, queue: List[QueueItem]) -> int: """ Check for available slot(s) based on given items in queue. """ now = datetime.now(gettz()) # register last_run for command /status message telegram.set_last_run(now) available = 0 for item in queue: # TODO: find out if the 10 days check is valid for all gyms if now < item.period.start <= (now + timedelta(10)) and not item.handled: top_logger.gym = item.gym available_slots = top_logger.available_slots(item.period) if available_slots: notify(telegram, item, available_slots) item.set_handled(True) available += len(available_slots) return available
def main(): config = ConfigParser() config.read("config.ini") # Enable logging logging.basicConfig(filename='app.log', filemode='w', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) spotify_remote = SpotifyRemote( config.get("SPOTIFY", "CLIENT_ID"), config.get("SPOTIFY", "CLIENT_SECRET"), config.get("SPOTIFY", "USERNAME"), ) personal_message_handler = PersonalMessageHandler() locations_handler = LocationsHandler() bot = TelegramBot(config.get("TELEGRAM", "TOKEN"), spotify_remote, personal_message_handler, locations_handler) bot.start_bot() try: while not sleep(1): pass except KeyboardInterrupt: pass bot.stop_bot()
def index(): req = request.get_json() bot = TelegramBot() bot.parse_webhook_data(req) # success = bot.action() message = bot.return_message() final_ans = income_message(str(message)) if (final_ans == 1): success = bot.send_message("Real new , You can safely forward") else: success = bot.send_message("Fake new , kindly report") return jsonify(success=success ) # TODO: Success should reflect the success of the reply
def main(tg_bot_token, model_dir, model_id): logging.basicConfig(level=logging.INFO) logging.info("Loading the model...") applier = load_model(model_id) logging.info(" Building bot...") bot = TelegramBot( tg_token=tg_bot_token, dump_dir=model_dir, ).set_applier(applier=applier, ) try: logging.info("Starting the bot...") bot.start() finally: bot.try_dump_history()
def main(args): if args.verbose: # Enable logging logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) # Get telegram token and get the corresponding bot token = getToken(args.salt_path, args.token_path, password=password) print('Token successfully acquired, logging in...') bot = TelegramBot(token, admin_id=admin_id, verbose=args.verbose) print('Logged in. Bot started.') # Start bot bot.start() bot.idle() if args.verbose: print('Bot stopped.')
def main(): config = configparser.ConfigParser() config.read("config.ini") DIR = config.get("LOCAL_STORAGE", "dir") if not os.path.exists(DIR): os.makedirs(DIR) chatbot = TelegramBot() chatbot.start_bot() procs = [ Process(target=p, args=[chatbot]) for p in [weekly_results_process, live_updates_process] ] [p.start() for p in procs] try: while not sleep(1): pass except KeyboardInterrupt: [p.kill() for p in procs] chatbot.stop_bot() raise SystemExit
def __init__(self, worker: Assigner): super(WindowAssigner, self).__init__(worker) self._telegram_bot: TelegramBot = TelegramBot()
ch.setLevel(logging.INFO) root_logger.addHandler(ch) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Utilities for booking RDV in 🇫🇷 prefectures') parser.add_argument('--nb-attempts', '-n', type=int, help='Number of attempts for chosen action(s)') parser.add_argument('--watch', default='website,email', help='What should be watched: `website` - checks dates on the prefecture website. `email` - checks gmail inbox for confirmation email') parser.add_argument('--config', default='hauts-de-seine-bio', help='Name of prefecture to watch dates for') parser.add_argument('--parallelism', default=1, type=int, help='Number of parallel threads checking for the same week') args = parser.parse_args() watch_types = set(args.watch.split(',')) setup_logging(LOG_PATH) logger = logging.getLogger("Global") tg_bot = TelegramBot() config = configs[args.config] logger.info(f'Using config for {args.config} prefecture') if not os.path.exists(DUMPS_FOLDER): os.makedirs(DUMPS_FOLDER) if not os.environ.get(WEBSITE_HOSTNAME): os.environ[WEBSITE_HOSTNAME] = f'localhost-main-{now()}' if 'email' in watch_types: store = CredentialsStore() def start_mail_checker_thread(email): mail_checker = MailChecker(store, email, config, tg_bot) return mail_checker.start_loop(args.nb_attempts)
from flask import Flask, request from telegram_bot import TelegramBot from config import TELEGRAM_INIT_WEBHOOK_URL app = Flask(__name__) TelegramBot.init_webhook(TELEGRAM_INIT_WEBHOOK_URL) @app.route("/webhook", methods=["POST"]) def index(): req = request.get_json() if "message" in req: bot = TelegramBot() response = bot.prepare_response(req) bot.send_message(response) else: response = {} return response if __name__ == "__main__": app.run(port=8080)
import telegram import time from telegram_bot import TelegramBot TOKEN = '138555076:AAECtCxHPmVXyKw9cc2-4yM73fJ7AOpJutE' if __name__ == '__main__': bot = TelegramBot(token=TOKEN) bot.run_events_loop()