def __init__(self): self.browser = webdriver.Chrome(chromedriver, options=chrome_options, seleniumwire_options=proxy_options) self.telegram = TelegramBot() self.max_likes = 20 self.likes_count = 0
def test_main(): with open("test-data.json") as f: sample_tweets = json.load(f) # Populate coins main.get_coins_bittrex() # Telegram bot bot = TelegramBot() # Twitter stream class MockTwitter: def tweet_callback(text, user, link): to_buy = main.analyze(text) assert len(to_buy) > 0 bot.notify_tweet(text, user, link, to_buy) tweets = [sample_tweets["tweet_image"], sample_tweets["tweet_text"]] count = 0 for tweet in tweets: Twitter.handle_tweet(MockTwitter, tweet_json=tweet) count += 1 while count < len(tweets): time.sleep(1)
def __init__(self, network=None, storage=None): config = Config() self.telegram_bot = TelegramBot(config.telegram_token) self.monitors = {} self.network = network or Network() self.storage = storage or Storage("monitors.json") self.load_existing_monitors()
def test_telegram_buy(): main.get_coins_bittrex() main.bot = TelegramBot() query_data = "buy_doge" try: replies = main.bot.get_query_replies(query_data) assert len(replies) > 0 assert len(replies[0]) == 2 assert type(replies[0][0]) is str except Exception as e: raise AssertionError(e)
def test_telegram_summary(): main.get_coins_bittrex() main.bot = TelegramBot() query_data = "summary_doge" try: replies = main.bot.get_query_replies(query_data) assert len(replies) > 0 assert len(replies[0]) == 2 assert type(replies[0][0]) is str assert type(replies[0][1]) is telepot.namedtuple.InlineKeyboardMarkup except Exception as e: raise AssertionError(e)
def __init__(self, token, url): self.bot = TelegramBot(token) self.bot.set_webhook(f'{url}/bot/{token}/') self.update_queue = Queue() self.dispatcher = Dispatcher(self.bot, self.update_queue, workers=4, use_context=True) self.update_obj = None self.__register_handlers__()
def __init__(self, logger, postgres): self._status = {} self._logger = logger self._postgres = postgres # self._updater = Updater(token=BOT_TOKEN, use_context=True) self._bot = TelegramBot(token=BOT_TOKEN) self._job_queue = JobQueue() self._update_queue = Queue() self._dispatcher = Dispatcher(self._bot, self._update_queue, use_context=True) self._translator = Translator(file=TRANSLATION_FILE) self._set_commands() self._load_status() self._set_job_queue()
def setup_dispatcher(token: str) -> 'Dispatcher': bot = TelegramBot(token=token) dispatcher = Dispatcher( bot=bot, update_queue=None, workers=0, use_context=True, ) dispatcher.add_handler(get_movie_handler()) dispatcher.add_handler(get_inline_handler()) return dispatcher
def process_webhook_event(token: str, request_body: bytes, dispatcher: 'Dispatcher' = None): if not isinstance(request_body, dict): request_body = json.loads(request_body) bot = TelegramBot(token=token) data = Update.de_json(request_body, bot) if dispatcher is None: dispatcher: 'Dispatcher' = get_dispatcher(token) dispatcher.process_update(data) return dispatcher
def __init__(self, events, data_handler): self.events = events self.config = load_config() self.data_handler = data_handler self.symbol_list = self.data_handler.symbol_list self.counter = 0 self.bars_window = 200 self.rsi_window = 14 self.telegram = TelegramBot( bot_token=self.config['telegram']['bot_token'], channel_id=self.config['telegram']['channel_id'])
def test_twitter_tweet_callback(run_forever): main.get_coins_bittrex() main.bot = TelegramBot() text = "please buy doge" user = "******" link = "https://twitter.com/mcafee2cash/status/944746808466698240" try: main.twitter_tweet_callback(text, user, link) except Exception as e: raise AssertionError(e) if run_forever: while True: time.sleep(1)
def __init__(self, config_file, data_file): self.config_file = config_file self.data_file = data_file self.saved_data = self._read_data_file() self._parse_config_file() self._check_system() self.state = RpisState(self) try: self.bot = TelegramBot(token=self.telegram_bot_token) except Exception as e: raise Exception( 'Failed to connect to Telegram with error: {0}'.format( repr(e))) logger.debug('Initialised: {0}'.format(vars(self)))
def webhook_handler(data): bot = TelegramBot(TG_TOKEN) dispatcher = Dispatcher(bot, None) # Handlers dispatcher.add_handler(CommandHandler('ni', callbacks.ni)) dispatcher.add_handler(CommandHandler('list', callbacks.ni_list)) dispatcher.add_handler(CommandHandler('add', callbacks.add)) dispatcher.add_handler(CommandHandler('edit', callbacks.edit)) dispatcher.add_handler(CommandHandler('delete', callbacks.delete)) dispatcher.add_handler(CommandHandler('cancel', callbacks.cancel)) dispatcher.add_handler(MessageHandler(Filters.text, callbacks.text_message)) # NOQA # Process update update = Update.de_json(data, bot) dispatcher.process_update(update)
def webhook_handler(data): bot = TelegramBot(settings.TG_TOKEN) dispatcher = Dispatcher(bot, None) # Handlers dispatcher.add_handler(CommandHandler('start', callbacks.start)) dispatcher.add_handler(CommandHandler('website', callbacks.website)) dispatcher.add_handler(CommandHandler('help', callbacks.help)) dispatcher.add_handler(CommandHandler('event', callbacks.get_event)) dispatcher.add_handler(CommandHandler('login', callbacks.login)) dispatcher.add_handler(CommandHandler('meeting', callbacks.meeting)) dispatcher.add_handler(CommandHandler('subscribe', callbacks.calendar)) dispatcher.add_handler( MessageHandler(Filters.text, callbacks.calendarSubscribe), ) dispatcher.add_handler(CallbackQueryHandler(callbacks.meeting_callback)) # Process update update = Update.de_json(data, bot) dispatcher.process_update(update)
def __init__(self, token=settings.BOT_TOKEN): self.bot = TelegramBot(token) self.dispatcher = None if settings.DEBUG: self.updater = Updater(token, use_context=True) self.dispatcher = self.updater.dispatcher self.updater.start_polling() else: self.bot.set_webhook('{}/{}/{}/'.format(settings.SITE_DOMAIN, 'bot', token)) self.dispatcher = Dispatcher(self.bot, None, workers=0, use_context=True) for handler in HANDLERS: self.dispatcher.add_handler(handler)
def init_bot(self): try: self.bot = TelegramBot() self.bot_command = None if check_connection(): poll_thread = Thread(target=self.poll_bot) poll_thread.setDaemon(True) poll_thread.start() bot_command_thread = Thread(target=self.handle_bot_commands) bot_command_thread.setDaemon(True) bot_command_thread.start() except Exception: self.Log("Error while initiating telegram bot.") time.sleep(5) self.restart_request = True self.init_bot()
def __init__(self): self.authorized = False self.ticks_history_received = False self.ticks_subscribed = False self.balance_subscribed = False self.in_deal = False self.symbols_showed = False #self.strategy = 'random' self.strategy = 'bollinger' self.account = {} self.balance = {} self.step = 1 self.loose_counter = 0 self.last_update = time.time() self.telegram = TelegramBot(token=TELEGRAM_TOKEN, proxies={'http': TELEGRAM_PROXY, 'https': TELEGRAM_PROXY}, chat_id=TELEGRAM_CHAT_ID) self.max_loose = 5 self.max_ticks = 100 self.max_timeout = 1200 self.symbol = 'R_50' # При смене контракта все надо обнулить (методом) self.min_bet = 0.35 #self.symbol = 'frxEURUSD' #self.min_bet = 0.50 self.ticks_data = [] self.deals_data = [] self.bollinger_bands_steps = 20 self.standard_deviations = 2 self.token = BOT_TOKEN self.config = {} # Настройки для игры
class Bot: TELEGRAM_BOT = TelegramBot(Config.telegram_token()) def __init__(self, network=None, storage=None): self.monitors = {} self.network = network or Network() self.storage = storage or Storage("monitors.json") self.load_existing_monitors() @property def commands(self): return [ # bot level CommandHandler("start", lambda *args: self.start(*args)), CommandHandler("stop", lambda *args: self.stop(*args)), # monitor level CommandHandler("all_stats", lambda *args: self.all_stats(*args)), CommandHandler("hashrates", lambda *args: self.hashrates(*args)), CommandHandler("gpu_temps", lambda *args: self.gpu_temps(*args)), CommandHandler("timestamp", lambda *args: self.timestamp(*args)), ] def load_existing_monitors(self): obj = self.storage.contents for (chat_id, panels) in obj.items(): monitor = Monitor(chat_id, self) monitor.panels = panels self.monitors[chat_id] = monitor def send_table(self, table, chat_id): text = str(tabulate(table)) self.send_message(text, chat_id, code=True) def send_message(self, text, chat_id, code=False): text = "```\n" + text + "\n```" if code else text Bot.TELEGRAM_BOT.send_message(text=text, chat_id=chat_id, parse_mode=ParseMode.MARKDOWN) def send_stats_for_chat(self, chat_id, included=[]): included = included or ["timestamp", "hashrate", "gpu_temps"] monitor = self.monitors.get(chat_id) if not monitor or not monitor.panels: error = "Get started by calling /start [panel_id]" return self.send_message(error, chat_id) monitor.send_stats(included) # actions def start(self, bot, update): cmd = update.effective_message.text.split(" ") if len(cmd) < 2 or len(cmd[1]) != 6: update.message.reply_text("please provide 6 character panel id") return chat_id = update.effective_chat.id if chat_id not in self.monitors: self.monitors[chat_id] = Monitor(chat_id, self) monitor = self.monitors[chat_id] monitor.panels.append(cmd[1]) self.storage.set(chat_id, monitor.panels) update.message.reply_text("Monitoring: " + repr(monitor.panels)) def stop(self, bot, update): cmd = update.effective_message.text.split(" ") if len(cmd) < 2 or len(cmd[1]) != 6: update.message.reply_text("please provide 6 character panel id") return chat_id = update.effective_chat.id monitor = self.monitors[chat_id] panel = cmd[1] if panel in monitor.panels: monitor.panels.remove(panel) self.storage.set(chat_id, monitor.panels) update.message.reply_text("Stopped monitoring: " + panel) else: update.message.reply_text("Panel not found: " + repr(monitor.panels)) def timestamp(self, bot, update): self.send_stats_for_chat(update.effective_chat.id, ["timestamp"]) def hashrates(self, bot, update): self.send_stats_for_chat(update.effective_chat.id, ["hashrate"]) def gpu_temps(self, bot, update): self.send_stats_for_chat(update.effective_chat.id, ["gpu_temps"]) def all_stats(self, bot, update): self.send_stats_for_chat(update.effective_chat.id) # scheduler def update(self): for monitor in self.monitors.values(): monitor.update()
from flask import Flask, request, jsonify from telegram import TelegramBot app = Flask(__name__) bot = TelegramBot() @app.route('/') def hello(): return '<h1>Hola esta es la pagina de Ivan Rodriguez</h1>' @app.route('/webhook', methods=['POST']) def webhook(): req = request.get_json() bot.parse_json(req) success = bot.action() return jsonify(success=success) if __name__ == '__main__': app.run(host='0.0.0.0')
from telegram import TelegramBot from spotify import SpotifyBot from difflib import SequenceMatcher import configparser as cfg parser = cfg.ConfigParser() parser.read('config.cfg') dummy_channel = parser.get('info', 'dummy_channel') target_channel = parser.get('info', 'target_channel') playlist_id = parser.get('info', 'playlist_id') print(type(dummy_channel), target_channel, playlist_id) tbot = TelegramBot(parser.get('creds', 'tel_token')) sbot = SpotifyBot(parser.get('creds', 'spot_token')) def similar(a, b): return SequenceMatcher(None, a, b).ratio() def spotify_search(audio): track = audio['title'] artist = audio['performer'] found = sbot.search_track(track[:25]) if 'tracks' not in found: print(track) print(found) return result = {'track': None, 'artist': None, 'id': None}
3. Determine which coins to buy """ coins = extract_symbols(text) sentiment, overall = get_sentiment_analysis(text, coins) to_buy = get_verdict(sentiment, overall) return to_buy def telegram_order_callback(coin, amount): print(coin, amount) def twitter_tweet_callback(text, user, link): to_buy = analyze(text) if len(to_buy) > 0: bot.notify_tweet(text, user, link, to_buy) if __name__ == "__main__": # Populate coins get_coins_bittrex() # Telegram bot bot = TelegramBot(order_callback=telegram_order_callback) # Twitter stream twitter = Twitter(tweet_callback=twitter_tweet_callback) while True: time.sleep(1)
def __init__(self, unique_id, task, model): super().__init__(unique_id, model) self.task = task self.model = model self.bot = TelegramBot()
def auto_message(): bot = TelegramBot(settings.TG_TOKEN) task.today(bot)
def auto_invite(event_id): bot = TelegramBot(settings.TG_TOKEN) task.invite_meeting(bot, event_id)
bot.send_message( chat, f"Ngrok is already running and available at {ngrok.get_public_url()}" ) else: bot.send_message( chat, "To start the ngrok instance, please enter your totp code:" ) expecting_authentication = True elif text == "/stop": if ngrok.is_running(): ngrok.stop() bot.send_message(chat, "The ngrok instance has been stopped.") else: bot.send_message(chat, "Ngrok is not running.") if env.get("TELEGRAM_BOT_TOKEN"): bot_owner = int(env["TELEGRAM_BOT_OWNER"]) telegram_bot = TelegramBot(env["TELEGRAM_BOT_TOKEN"]) telegram_bot.send_message( bot_owner, f"{hostname} is now up and running. Type /start to forward port {ngrok.port} via ngrok." ) telegram_bot.run(on_update) else: print(ngrok.start()) while True: time.sleep(1)
from web_server import create_web_server if __name__ == "__main__": pid = str(os.getpid()) with open('application.pid', 'w') as f: f.write(pid) TELEGRAM_TOKEN = os.environ.get('TOKEN') WEB_PORT = os.environ.get('WEB_PORT', 8080) LOG_LEVEL = os.environ.get('LOG_LEVEL', 'INFO') if not TELEGRAM_TOKEN: raise EmptyTokenError() else: logger.init("telegram-bot.log", dir_name="logs", log_level=LOG_LEVEL) logging.info(f"application pid : {pid}") logging.info(f"TOKEN : {TELEGRAM_TOKEN}") logging.info(f"WEB_PORT : {WEB_PORT}") logging.info(f"LOG_LEVEL : {LOG_LEVEL}") web_server_to_telegram_queue = asyncio.Queue() create_web_server(web_server_to_telegram_queue).listen(WEB_PORT) logging.info(f"Web server started on {WEB_PORT}") TelegramBot(TELEGRAM_TOKEN, web_server_to_telegram_queue).run() asyncio.get_event_loop().run_forever()
from correios import Correios from telegram import TelegramBot bot = TelegramBot('1409626650:AAHTdjbu64aG23T2OaRdoBNCenrNwAzRBJk') correios = Correios( 'teste', '1abcd00b2731640e886fb41a8a9671ad1434c599dbaa0a0de9a5aa619f29a83f') encomendas_cache = {} def build_response(chat_id, mensagem, is_primeira): if mensagem == '/start' or is_primeira: return ( '🤖💬 Bem vindo ao bot de rastreamento de encomendas. \nPara fazer um novo rastreamento, envie apenas o código (13 dígitos):' ) elif len(mensagem) != 13: return ( '🤖💬 Quantidade de dígitos inválidos, por favor, digite apenas o código (13 dígitos):' ) rastreamento = correios.rastrear(mensagem) if rastreamento is not None and len(rastreamento["eventos"]) > 0: ultimo_evento = rastreamento["eventos"][0] encomendas_cache[rastreamento["codigo"]] = { "status": ultimo_evento["status"], "chat_id": chat_id, "ultimo": rastreamento["ultimo"] }