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
class Worker(Agent): """An agent for realise tasks""" def __init__(self, unique_id, task, model): super().__init__(unique_id, model) self.task = task self.model = model self.bot = TelegramBot() def step(self): db = db_manager() try: self.task.func(self.task.params, self.task.customer) d = { 'Datetime': dt.datetime.now(), 'Task name': self.task.name, 'Worker': self.unique_id, 'Status': 'Done', 'Customer': self.task.customer, 'System': self.task.system } df = pd.DataFrame(data=d, index=[0]).set_index('Datetime') db.insert_into_db(df=df) fcf.last_worker_datetime.update( {self.task.name: dt.datetime.now()}) try: if self.task.params['push_it'] == True: self.bot.send_group_message(self.task.name + ' done') except: pass except Exception as e: err = str(traceback.format_exc()) d = { 'Datetime': dt.datetime.now(), 'Task name': self.task.name, 'Worker': self.unique_id, 'Status': 'Error', 'Customer': self.task.customer, 'System': self.task.system } df = pd.DataFrame(data=d, index=[0]).set_index('Datetime') db.insert_into_db(df=df) try: if self.task.params['push_it'] == True: self.bot.send_group_message(self.task.name + ' error: ' + err) except: pass finally: db.close()
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_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 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 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, 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 __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 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 __init__(self, irc): super(TelegramBridge, self).__init__(irc) self.log.debug("initualizing") self._tgChatId = self.registryValue("tgChatId") self._tgToken = self.registryValue("tgToken") try: self._tgId = int(self._tgToken.split(":", 1)[0]) except ValueError: self.log.error("failed to parse tgToken, please check it is in " "the <ID>:<COOKIE> format") self._tgTimeout = self.registryValue("tgTimeout") self._tgTargetChannel = None self._tgIrc = None self._tg = TelegramBot(self._tgToken)
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 = {} # Настройки для игры
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 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)
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()
def __init__(self, unique_id, task, model): super().__init__(unique_id, model) self.task = task self.model = model self.bot = TelegramBot()
def auto_invite(event_id): bot = TelegramBot(settings.TG_TOKEN) task.invite_meeting(bot, event_id)
def auto_message(): bot = TelegramBot(settings.TG_TOKEN) task.today(bot)
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()
class BBRSI(Strategy): def __init__(self, events, data_handler, portfolio): self.events = events self.config = load_config() self.data_handler = data_handler self.symbol_list = self.data_handler.symbol_list self.portfolio = portfolio self.counter = 0 self.bars_window = 200 self.rsi_window = 14 self.div_window = 200 self.ma_short = 20 self.ma_long = 90 self.telegram = TelegramBot( bot_token=self.config['telegram']['bot_token'], channel_id=self.config['telegram']['channel_id']) def calculate_signals(self): for symbol in self.symbol_list: print(f'Searching for {symbol} signals ...') timestamps = self.data_handler.get_latest_bars_values( symbol, 'datetime', N=self.bars_window) highs = self.data_handler.get_latest_bars_values( symbol, 'high', N=self.bars_window) lows = self.data_handler.get_latest_bars_values(symbol, 'low', N=self.bars_window) closes = self.data_handler.get_latest_bars_values( symbol, 'close', N=self.bars_window) hlc3 = (highs + lows + closes) / 3 print(closes) signal_timestamp = timestamps[-1] rsi = RSI(closes, timeperiod=self.rsi_window) ma_short = EMA(hlc3, timeperiod=self.ma_short)[-1] ma_long = EMA(hlc3, timeperiod=self.ma_long)[-1] # Buy Signal conditions if ma_short < ma_long: trend = 'Short-term bearish' print(f'{symbol}: {trend}') bullish_div = bull_div( lows, rsi, timestamps, window=self.div_window, price_prominence=ma_long * 0.001, ) hbearish_div = hbear_div( highs, rsi, timestamps, window=self.div_window, price_prominence=ma_long * 0.001, ) if bullish_div and len(bullish_div) > 1: div_type = 'BULLISH' print(f'{symbol} - {div_type}: {signal_timestamp}') self.telegram.send_text({ 'symbol': symbol, 'timeframe': self.data_handler.timeframe, 'div_type': div_type, 'peaks': bullish_div, 'trend': trend, 'ma_short': ma_short, 'ma_long': ma_long }) elif hbearish_div and len(hbearish_div) > 1: div_type = 'HIDDEN BEARISH' print(f'{symbol} - {div_type}: {signal_timestamp}') self.telegram.send_text({ 'symbol': symbol, 'timeframe': self.data_handler.timeframe, 'div_type': div_type, 'peaks': hbearish_div, 'trend': trend, 'ma_short': ma_short, 'ma_long': ma_long }) elif ma_short > ma_long: trend = 'Short-term bullish' print(f'{symbol}: {trend}') bearish_div = bear_div( highs, rsi, timestamps, window=self.div_window, price_prominence=ma_long * 0.001, ) hbullish_div = hbull_div( lows, rsi, timestamps, window=self.div_window, price_prominence=ma_long * 0.001, ) if bearish_div and len(bearish_div) > 1: div_type = 'BEARISH' print(f'{symbol} - {div_type}: {signal_timestamp}') self.telegram.send_text({ 'symbol': symbol, 'timeframe': self.data_handler.timeframe, 'div_type': div_type, 'peaks': bearish_div, 'trend': trend, 'ma_short': ma_short, 'ma_long': ma_long }) elif hbullish_div and len(hbullish_div) > 1: div_type = 'HIDDEN BULLISH' print(f'{symbol} - {div_type}: {signal_timestamp}') self.telegram.send_text({ 'symbol': symbol, 'timeframe': self.data_handler.timeframe, 'div_type': div_type, 'peaks': hbullish_div, 'trend': trend, 'ma_short': ma_short, 'ma_long': ma_long })
class Momentum(Strategy): 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 calculate_signals(self): for symbol in self.symbol_list: print('Searching for {1} signals ...'.format(symbol)) last_price = self.data_handler.current_price(symbol)[0] h1_highs = self.data_handler.get_latest_bars_values( symbol, 'high', timeframe='H1', N=self.bars_window) h1_lows = self.data_handler.get_latest_bars_values( symbol, 'low', timeframe='H1', N=self.bars_window) h1_closes = self.data_handler.get_latest_bars_values( symbol, 'close', timeframe='H1', N=self.bars_window) h1_hlc3 = (h1_highs + h1_lows + h1_closes) / 3 h1_ema_50 = EMA(h1_hlc3, timeperiod=50) h1_ema_100 = EMA(h1_hlc3, timeperiod=100) h1_ema_200 = EMA(h1_hlc3, timeperiod=200) m15_highs = self.data_handler.get_latest_bars_values( symbol, 'high', timeframe='m15', N=self.bars_window) m15_lows = self.data_handler.get_latest_bars_values( symbol, 'low', timeframe='m15', N=self.bars_window) m15_closes = self.data_handler.get_latest_bars_values( symbol, 'close', timeframe='m15', N=self.bars_window) m15_hlc3 = (m15_highs + m15_lows + m15_closes) / 3 m15_ema_50 = EMA(m15_hlc3, timeperiod=50) m15_ema_100 = EMA(m15_hlc3, timeperiod=100) m15_ema_200 = EMA(m15_hlc3, timeperiod=200) m15_price_bb_up, m15_price_bb_mid, m15_price_bb_low = BBANDS( m15_hlc3, timeperiod=20, nbdevup=2, nbdevdn=2) m15_price_bb_low_dist = (m15_price_bb_mid + m15_price_bb_low) / 2 m15_price_bb_up_dist = (m15_price_bb_up + m15_price_bb_mid) / 2 m15_rsi = RSI(m15_closes, timeperiod=14) m15_rsi_bb_up, m15_rsi_bb_mid, m15_rsi_bb_low = BBANDS( m15_rsi, timeperiod=20, nbdevup=2, nbdevdn=2) m15_stochrsi = STOCHRSI(pd.Series(m15_closes), timeperiod=14) m15_atr = ATR(m15_highs, m15_lows, m15_closes, timeperiod=14) datetime = self.data_handler.get_latest_bar_datetime(symbol)[0] direction = None status = None position = 'Not yet' print(datetime) if last_price > h1_ema_50[-1] and last_price > h1_ema_100[ -1] and last_price > h1_ema_200[-1]: print('Uprend detected') if last_price > m15_ema_50[-1] and last_price > m15_ema_100[ -1] and last_price > m15_ema_200[-1]: print('Uprend confirmed') direction = 'LONG' if m15_rsi[-1] < m15_rsi_bb_low[-1]: print('Reversal Detected') status = 'Reversal detected' if last_price < m15_price_bb_low_dist[-1]: print('Reversal confirmed') status = 'Reversal confirmed' if m15_stochrsi[-1] < 25: print('Go LONG') position = 'Go ahead' elif last_price < h1_ema_50[-1] and last_price < h1_ema_100[ -1] and last_price < h1_ema_200[-1]: print('Downrend detected') if last_price < m15_ema_50[-1] and last_price < m15_ema_100[ -1] and last_price < m15_ema_200[-1]: print('Downrend confirmed') direction = 'SHORT' if m15_rsi[-1] > m15_rsi_bb_up[-1]: print('Reversal Detected') status = 'Reversal detected' if last_price > m15_price_bb_up_dist[-1]: print('Reversal confirmed') status = 'Reversal confirmed' if m15_stochrsi[-1] > 75: print('Go SHORT') position = 'Go ahead' else: pass print(symbol, direction, status, position, datetime) if status is not None: self.telegram.send_text({ 'symbol': symbol, 'direction': direction, 'status': status, 'position': position, 'atr': np.around(m15_atr[-1], decimals=5), 'datetime': datetime })
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)
class InstagramBot: main_url = 'https://www.instagram.com' hashtag_url = 'https://www.instagram.com/explore/tags/' scroll_script = "window.scrollTo(0, document.body.scrollHeight);" like_button_xpath = '/html/body/div[1]/section/main/div/div[1]/article/div[3]/section[1]/span[1]/button' wrong_userpage = '/html/body/div[1]/section/main/div/h2' post_count_xpath = '/html/body/div[1]/section/main/div/header/section/ul/li[1]/span/span' closed_account_xpath = '/html/body/div[1]/section/main/div/div/article/div[1]/div/h2' subscribe_button = '/html/body/div[1]/section/main/div/header/section/div[1]/div[1]/div/div/button' subscribe_button2 = '/html/body/div[1]/section/main/div/header/section/div[2]/div/div/div/button' comments_xpath = '/html/body/div[1]/section/main/div/div[1]/article/div[3]/div[1]/ul' comment_author_xpath = '/html/body/div[1]/section/main/div/div[1]/article/header/div[2]/div[1]/div[1]/span/a' comment_author_xpath_2 = '/html/body/div[1]/section/main/div/div[1]/article/header/div[2]/div[1]/div[1]/a' comment_pattern = 'цена|стоимость|стоит|сколько|цены|цену|цене' author = 'sovenok__krd' 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 close_browser(self): self.browser.close() self.browser.quit() def login(self, username, password): browser = self.browser browser.get(self.main_url) time.sleep(random.randrange(3, 5)) print(browser.title) if os.path.exists(f"{cookies}"): print("Куки найдены!") for cookie in pickle.load(open(f"{username}_cookies", "rb")): browser.add_cookie(cookie) time.sleep(5) browser.refresh() time.sleep(10) else: username_input = browser.find_element_by_name('username') username_input.clear() username_input.send_keys(username) time.sleep(2) password_input = browser.find_element_by_name('password') password_input.clear() password_input.send_keys(password) password_input.send_keys(Keys.ENTER) time.sleep(5) # cookies pickle.dump(browser.get_cookies(), open(f"{username}_cookies", "wb")) print("Куки созданы!") # получаем список url страниц авторов комментариев к посту def get_comment_autor_urls(self): try: if self.xpath_exists(self.comment_author_xpath): author = self.browser.find_element_by_xpath( self.comment_author_xpath).text else: author = self.browser.find_element_by_xpath( self.comment_author_xpath_2).text if author == self.author: return [] comments = self.browser.find_element_by_xpath(self.comments_xpath) spans = comments.find_elements_by_tag_name('span') # собираем не пустые span в которых спрашивают про стоимость spans = [ item for item in spans if item.text != '' and re.search(self.comment_pattern, item.text.lower()) ] # Составляем список тегов 'a' которые относятся к родительскому элементу тега span, # кроме ссылки на автора поста hrefs = [] for span in spans: parent_element = span.find_element_by_xpath('..') all_tags_a = parent_element.find_elements_by_tag_name('a') for a in all_tags_a: if a.text != author: hrefs.append(a) # hrefs = comments.find_elements_by_tag_name('a') hrefs = [ item.get_attribute('href') for item in hrefs if "/p/" not in item.get_attribute('href') and "/tags/" not in item.get_attribute('href') ] except Exception as ex: print(ex) return None else: return list(set(hrefs)) # будем заходить на рандомный пост из найденных, получать все комментарии и лайкать посты их авторов def like_photo_by_hashtag(self, hashtag): browser = self.browser hashtag_page_loops_count = 20 # сколько скролов делать на странице с хештегами user_page_loops_count = 5 # сколько скролов делать на странице пользователя user_posts_count = 2 # сколько постов каждого пользователя лакать hashtag_posts_count = 150 # сколько постов на странице с хештегами выбирать # для отправки в телегу telegram_data = { 'hashtag': hashtag, 'select_posts': [], 'users': [], 'like_posts': [], 'subscribers': [], } browser.get(f'{self.hashtag_url}{hashtag}/') time.sleep(5) post_urls = self.get_post_urls(loops_count=hashtag_page_loops_count) try: posts = random.sample(post_urls, hashtag_posts_count) except ValueError: print('Похоже, мы не авторизированы.') self.close_browser() return # ходим пока не наберем нужное колличество лайков post_number = 0 while self.likes_count < self.max_likes: post_number += 1 print(f'Пост {post_number} лайков поставлено {self.likes_count}') try: post = posts.pop() except IndexError: print('Закончились посты, выхожу.') break print(f'Выбран пост: {post}') browser.get(post) time.sleep(random.randrange(10, 20)) hrefs = self.get_comment_autor_urls( ) # Получаем список пользователей которых надо лайкнуть if hrefs is None: break if hrefs: print(f'Список пользователей для лайков: {hrefs}') telegram_data['select_posts'].append(post) # Поочередно лайкаем посты пользователя for href in hrefs: # если уже наброно нужное колличество лайков, выходим if self.likes_count >= self.max_likes: print('Мы набрали нужное колличество лайков.Выходим.') break account = href.split("/")[-2] # Если мы уже лайкали этого пользователя if account in telegram_data['users']: print(f'Мы уже лайкали пользователя {account}') continue telegram_data['users'].append(account) browser.get(href) time.sleep(5) if self.xpath_exists(self.wrong_userpage): print('Такого пользователя не существует') continue elif self.xpath_exists(self.closed_account_xpath): print(f'Это закрытый аккаунт! Подписываемся на {account}') self.subscribe_to_account() telegram_data['subscribers'].append(account) time.sleep(3) continue else: print( f'Пользователь {account} успешно найден, ставим лайки!' ) time.sleep(3) post_urls = self.get_post_urls( loops_count=user_page_loops_count) try: post_urls = random.sample(post_urls, user_posts_count) except ValueError: print('На странице недостаточно постов') else: print(f'Выбраны случайные посты: {post_urls}') self.like_posts(post_urls) telegram_data['like_posts'].extend(post_urls) time.sleep(3) self.close_browser() self.telegram.send_notification(telegram_data) def xpath_exists(self, url): # проверяем по xpath существует ли элемент на странице browser = self.browser try: browser.find_element_by_xpath(url) exist = True except NoSuchElementException: exist = False return exist # ставим лайк на пост по прямой ссылке def put_exactly_like(self, userpost): browser = self.browser browser.get(userpost) time.sleep(4) if self.xpath_exists(self.wrong_userpage): print('Такого поста не существует') self.close_browser() else: print('Пост успешно найден, ставим лайк!') time.sleep(2) browser.find_element_by_xpath(self.like_button_xpath).click() time.sleep(2) print(f'Лайк на пост: {userpost} поставлен!') self.close_browser() # получаем колличество постов на странице юзера def get_posts_count(self): post_count = self.browser.find_element_by_xpath( self.post_count_xpath).text post_count = post_count.replace(' ', '') return int(post_count) // 12 # Получаем список с url постов пользователя def get_post_urls(self, loops_count=1): browser = self.browser post_urls = [] for i in range(0, loops_count): hrefs = browser.find_elements_by_tag_name('a') hrefs = [ item.get_attribute('href') for item in hrefs if "/p/" in item.get_attribute('href') ] for href in hrefs: post_urls.append(href) browser.execute_script(self.scroll_script) time.sleep(random.randrange(2, 4)) return list(set(post_urls)) # лайкаем каждый пост из списка def like_posts(self, post_urls): browser = self.browser for post_url in post_urls: try: browser.get(post_url) time.sleep(5) browser.find_element_by_xpath( self.like_button_xpath).send_keys(Keys.ENTER) time.sleep(random.randrange(80, 100)) self.likes_count += 1 print(f'Лайк на пост: {post_url} поставлен!') except Exception as ex: print(ex) self.close_browser() # ставим слайки по ссылке на аккаунт пользователя def put_many_likes(self, user_page): browser = self.browser browser.get(user_page) time.sleep(4) if self.xpath_exists(self.wrong_userpage): print('Такого пользователя не существует') self.close_browser() return elif self.xpath_exists(self.closed_account_xpath): print('Это закрытый аккаунт') self.subscribe_to_account() self.close_browser() return else: print('Пользователь успешно найден, ставим лайки!') time.sleep(2) loops_count = self.get_posts_count() post_urls = self.get_post_urls(loops_count=loops_count) self.like_posts(post_urls) self.close_browser() def subscribe_to_account(self): browser = self.browser time.sleep(3) try: if self.xpath_exists(self.subscribe_button): browser.find_element_by_xpath(self.subscribe_button).send_keys( Keys.ENTER) else: browser.find_element_by_xpath( self.subscribe_button2).send_keys(Keys.ENTER) time.sleep(3) except Exception as ex: print(ex) self.close_browser() def selection_of_posts(self, hashtag: str, loops_count: int, post_sample: int): """ Заходим по рандомному хештегу, выбирает рандомное колличество постов, проверяем их на наличее нужных нам комментариев и составляем список. :loops_count: колличество скролов страницы хештегов :post_sample: сколько рандомных постов выбираем для проверки """ browser = self.browser posts_count = 0 max_posts = 20 # список постов для отправки в телегу select_posts = [] print(f'Хештег {hashtag}') browser.get(f'{self.hashtag_url}{hashtag}/') time.sleep(random.randrange(8, 16)) print(browser.title) post_urls = self.get_post_urls(loops_count=loops_count) print(f'Постов отобрано: {post_urls}') try: posts = random.sample(post_urls, post_sample) except ValueError: print('Не открывается страница с хештегами.') self.close_browser() return # ходим пока не наберем нужное колличество подхлдящих постов while posts_count < max_posts: print(f'собрано постов {posts_count}') try: post = posts.pop() except IndexError: print('Закончились посты, выхожу.') break print(f'Выбран пост: {post}') browser.get(post) time.sleep(random.randrange(8, 16)) hrefs = self.get_comment_autor_urls() if hrefs: print(f'Подходящий пост. {post}') select_posts.append(post) posts_count += 1 # если уже наброно нужное колличество постов, выходим if posts_count >= max_posts: print('Мы набрали нужное колличество постов.Выходим.') break self.close_browser() self.telegram.send_notification(select_posts, only_posts=True)
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}
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)
class StateMachine: 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 = {} # Настройки для игры def auth(self): """Авторизация""" return json.dumps({ 'authorize': self.token, }) def ping(self): """Пинг для поддержания соединения""" return json.dumps({ 'ping': 1 }) def get_active_symbols(self): return json.dumps({ 'active_symbols': 'brief', 'product_type': 'basic', }) def get_ticks_history(self) -> str: """Получить историю по тикам""" return json.dumps({ 'ticks_history': self.symbol, 'end': 'latest', 'start': 1, 'style': 'ticks', 'adjust_start_time': 1, 'count': self.max_ticks, }) def subscribe_ticks(self): """Подписаться на обновления тиков потоком""" return json.dumps({ 'ticks': self.symbol, 'subscribe': 1, }) def subscribe_balance(self): """Подписаться на обновления баланса потоком""" return json.dumps({ 'balance': 1, 'account': 'current', 'subscribe': 1, }) def save_new_ticks(self, symbol: str, history: list): """Записываем массив тиков""" if not symbol == self.symbol: logger.error('[ERROR]: symbol %s is incorrect, we wanna %s' % (symbol, self.symbol)) return self.ticks_data = [] self.deals_data = [] if not history: return for i, item in enumerate(history['prices']): tick = { 'symbol': symbol, 'quote': item, 'epoch': history['times'][i], } self.save_new_tick(tick, with_pop = False) def save_new_tick(self, tick: dict, with_pop: bool = True): """Сохранение в массив нового тика :param tick: тик :param with_pop: Удалить первый тик""" if not tick['symbol'] == self.symbol: logger.error('[ERROR]: symbol %s is incorrect, we wanna %s' % (tick['symbol'], self.symbol)) return self.ticks_data.append([tick['epoch'], tick['quote']]) if with_pop: self.ticks_data.pop(0) # Докидываем боллинджера в тик # третий элемент массива в # каждом тике со словарем prices = [item[1] for item in self.ticks_data] for i, cur_tick in enumerate(self.ticks_data): if len(cur_tick) < 3: # Линии болленджера # top, middle, bottom bb = MathOperations.bollinger_bands(prices, i, self.bollinger_bands_steps, self.standard_deviations) cur_tick.append(bb) def playboy(self, reverse: bool = False): """Играем по настройкам Покупка => Цена пересекает среднюю линию канала Боллинджера или касается ее После этого касается крайней линии канала Боллинджера + Покупка делается противоположно :param reverse: для реверсивной покупки""" # Ищем по контракту последнюю сделку, # от нее считать будем strategy = self.config.get('strategy') if strategy == 1: self.strategy = 'bollinger' elif strategy == 2: self.strategy = 'random' else: self.strategy = '' CALL = 'CALL' PUT = 'PUT' if reverse: CALL = 'PUT' PUT = 'CALL' # Случайная стратегия, просто для проверки if self.strategy == 'random': types = (CALL, PUT) return self.buy_from_playboy(types[random.randint(0, len(types)-1)]) elif self.strategy == 'bollinger': result = strategy_opposite_touches(self.ticks_data) if result['action']: return self.buy_from_playboy(result['action']) def buy_from_playboy(self, direction): """Делаем ставку, что там по мартингейлу?""" self.in_deal = True self.last_update = time.time() amount = self.calc_rates() return json.dumps({ 'price': amount, 'buy': 1, 'subscribe': 1, 'parameters': { 'contract_type': direction, 'symbol': self.symbol, 'duration_unit': 't', 'duration': 5, 'basis': 'stake', 'currency': 'USD', 'amount': amount, } }) def calc_rates(self): digit = self.min_bet #0.35 multiply = 2 # Если умудрились max раз подряд всрать пишем в статистику #if self.step > self.stats_data.max_loose_in_sequence: # self.stats_data.max_loose_in_sequence = self.step while self.step > self.max_loose: self.step = self.step - self.max_loose result = MathOperations.martingail(digit, self.step, multiply) return round(result, 2) def follow_deal(self, deal): """Следим за сделкой - правильно ее закрываем :param deal: новая информация о сделке""" for i in range(len(self.deals_data)): if self.deals_data[i]['contract_id'] == deal['contract_id']: self.deals_data[i] = deal transactions = deal.get('transaction_ids') if 'sell' in transactions: self.in_deal = False profit = deal['profit'] if profit < 0: self.step += 1 self.loose_counter += 1 else: self.step = 1 self.loose_counter = 0 msg = '%s %s, profit %s, balance %s' % (BOT_TOKEN, deal.get('status'), profit, self.balance.get('balance')) logger.info(msg) self.telegram.send_message(msg) self.make_deal_report() # отчет по сделкам def make_deal_report(self): """Создать отчет через plotly, отправить сообщение в телегу """ output_img = save_with_plotly(ticks=self.ticks_data, image='png') with open(output_img, 'rb') as f: self.telegram.send_photo(f) if output_img.endswith('.png'): os.unlink(output_img) def refresh(self): """Мягкий перезапуск""" self.authorized = False self.ticks_history_received = False self.ticks_subscribed = False self.balance_subscribed = False self.account = {} self.ticks_data = [] # TODO: если мы были в сделке обыграть if self.in_deal and self.deals_data: logger.info('[IN DEAL]: %s' % (json_pretty_print(self.deals_data.pop()))) self.in_deal = False self.last_update = time.time() logger.info('[REFRESH STATE MACHINE]') def check_pulse(self): """Проверить, что обновления идут""" if time.time() - self.last_update > self.max_timeout: return False return True def set_settings(self, obj: dict = None): """Очищаем настройки по стратегии""" if not obj: # Была стратегия (остановка) if self.config.get('strategy', '') != '': self.telegram.send_message('Закончил играть!') self.config['strategy'] = '' if 'start' in self.config: del self.config['start'] if 'end' in self.config: del self.config['end'] else: # Не было стратегии (запуск) if self.config.get('strategy', '') == '': self.telegram.send_message('Начал играть!') # Была стратегии и сменилась elif self.config.get('strategy', '') != obj.get('strategy'): self.telegram.send_message('Сменил стратегию!') self.config.update(obj) def update_settings(self, interval: int = 10): """Обновить настройки, делаем раз в interval тиков""" last_update = self.config.get('last_update', interval) last_update += 1 if last_update > interval: try: self.config['last_update'] = 0 urla = '%s/binary_com/get_schedule/' % API_URL r = requests.get(urla, params={ 'token': BOT_TOKEN, }) resp = r.json() if resp: self.set_settings(resp) else: self.set_settings() except Exception: self.set_settings() err = 'Не удалось получить настройки' logger.exception(err) self.telegram.send_message(err) return self.config['last_update'] = last_update
class TelegramBridge(callbacks.Plugin): """Add the help for "@plugin help TelegramBridge" here This should describe *how* to use this plugin.""" _pipe = None def __init__(self, irc): super(TelegramBridge, self).__init__(irc) self.log.debug("initualizing") self._tgChatId = self.registryValue("tgChatId") self._tgToken = self.registryValue("tgToken") try: self._tgId = int(self._tgToken.split(":", 1)[0]) except ValueError: self.log.error("failed to parse tgToken, please check it is in " "the <ID>:<COOKIE> format") self._tgTimeout = self.registryValue("tgTimeout") self._tgTargetChannel = None self._tgIrc = None self._tg = TelegramBot(self._tgToken) def _feedToSupybot(self, author, text): newMsg = ircmsgs.privmsg(self._tgTargetChannel, text.encode("utf8", "replace")) newMsg.prefix = self._tgIrc.prefix.encode("utf8", "replace") newMsg.tag("from_telegram") newMsg.nick = author.encode("ascii", "replace") self.log.debug("feeding back to supybot: %s", newMsg) self._tgIrc.feedMsg(newMsg) def _validTgChat(self, message): chat = message.get("chat") if chat and chat.get("id") == self._tgChatId: return True return False def _tgUserRepr(self, user): id = user.get("id", "??") last_name = user.get("last_name", "") name = user.get("first_name", str(id)) + last_name chosen = user.get("username", name) return id, chosen def _tgHandleText(self, message): text = message.get("text", "") if not text: for type in ("photo", "video", "audio", "sticker", "contact", "location"): if message.get(type): text = "<%s>" % (type) user = message.get("from") id, author = self._tgUserRepr(user) if id != self._tgId: for line in text.splitlines(): repr = "%s> %s" % (author, line) self._sendIrcMessage(repr) self._feedToSupybot(author, line) def _telegramDiscardPreviousUpdates(self): update_id = None for update_id, update in self._tg.updates(): pass all(self._tg.updates(state=update_id)) def _telegramLoop(self): self._telegramDiscardPreviousUpdates() while True: try: for message in self._tg.updatesLoop(self._tgTimeout): if self._validTgChat(message): self._tgHandleText(message) except Exception, e: self.log.critical("%s", traceback.format_exc()) self.log.critical("%s", str(e)) time.sleep(1)