def message_new_posts(): # Retrieve new posts new_posts = get_new_posts() if(len(new_posts) <= 0): print("There aren't any new posts") return # Send messages for post in new_posts: # Preprocess message post['text'] = telegram.escape_text(shorten_text(post['text'])) if len(post['text']) > 0: post['text'] += "\n\n" # "Read on facebook" spacing only if there is some text post['text'] += "🔎 [Leggi su Facebook]({})".format(post['post_url']) # Send message if('images' in post): telegram.send_photos_url(post['text'], post['images']) # elif('video' in post): # pass elif('image' in post): telegram.send_photo_url(post['text'], post['image']) else: telegram.send_message(post['text']) # Update post db so that new posts are not re-posted for post in new_posts: db.insert({'post_id': post['post_id']}) print("inserted post {} in db".format(post['post_id']))
def ping_all(server_id): for server in servers_global: if server.id == server_id: print srv = db.session.query(Server).filter(Server.id == server_id).first() try: url = 'http://' + server.hostname rsp = requests.get(url, timeout=100) response = {'code': rsp.status_code, 'date': datetime.now().replace(microsecond=0)} except: response = {'code': 500, 'date': datetime.now().replace(microsecond=0)} now = datetime.now().replace(microsecond=0) time_limit = 60*60*1 # hour minute secondes if not srv.last_alert: delta = time_limit else: print(srv.hostname) delta = now - srv.last_alert delta = delta.total_seconds() if delta >= time_limit: message = "Alert ! server {alias} on http://{hostname} is down ! ".format( alias=srv.alias, hostname=srv.hostname) srv.last_alert = now tlg.send_message(srv.user.chat_id, TELEGRAM_TOKEN,message) new_log = Log(code=response['code'], date=response['date'], server_id = server.id ) db.session.add(new_log) srv.last_status = response['code'] db.session.commit()
def get_item_news(html_code): html = get_html_item_news(html_code) if html is None: return False header = html.h1.text words = '' text = html.find(class_='js-mediator-article _1YOxdQ').find_all('span') for t in text: if t.find(class_='_3trnLJ'): t.extract() else: text_clean = clean_text(t.get_text()) words = words + '\t' + text_clean + '\n' id = db.add_text(words, header, html_code['href']) words = words + '[Читать](https://t.me/iv?url=http%3A%2F%2Fzheev.ru/' + str( id) + '&rhash=77b201111b95b2)' send_message(words, header)
def on_send(self, event): selected = [self.m_list.GetFirstSelected()] while True: next = self.m_list.GetNextSelected(selected[-1]) if next == -1: break selected.append(next) selected = [self.groups[i] for i in selected] typed = self.m_textinput.GetValue() times = self.m_spinCtrl1.GetValue() for chat in selected: telegram.send_message(chat, typed, loop=times) self.m_textinput.SetValue('') dlg = wx.MessageDialog(self, f'Texto digitado: {typed}', 'Mensagem enviada', wx.OK ) dlg.ShowModal() dlg.Destroy()
def main(): poke_api = PokeApi() # Update the list of subscribers. telegram.update_subscriptions() # Map image captions image_dictionary = { 'back_default': 'Back', 'back_shiny': 'Back Shiny', 'front_default': 'Front', 'front_shiny': 'Front Shiny', 'back_female': 'Female Back', 'back_shiny_female': 'Female Back Shiny', 'front_female': 'Female Front', 'front_shiny_female': 'Female Front Shiny' } # Get a random Pokemon. pokemon = poke_api.get_random_pokemon() for image in pokemon['sprites']: # Load the name of the image. image_name = '<strong>' + pokemon[ 'name'] + ':</strong> ' + image_dictionary[image] # Send the image to the subscribed users. telegram.send_image(pokemon['sprites'][image], image_name, 'HTML', True) # Generate the message body. message = '<strong>' + pokemon['name'] + '</strong>' +\ "\n" + '-------------------------' +\ "\n" + '<b>Order:</b> ' + str(pokemon['order']) +\ "\n" + '<b>Height:</b> ' + str(pokemon['height']) +\ "\n" + '<b>Weight:</b> ' + str(pokemon['weight']) +\ "\n" + '<b>Abilities:</b> ' + ', '.join(poke_utils.get_abilities(pokemon)) +\ "\n" + '<b>Moves:</b> ' + ', '.join(poke_utils.get_moves_with_link(pokemon)) # Send the message to the subscribed users. telegram.send_message(message, 'HTML')
def create_new_key(tmsg, token, issue_id=None): """ Creates and sends new key for the user and :param tmsg: Telegram message :param token: Telegram bot token :param issue_id: User's issue connecting to server """ try: new_key = api.get_new_key(user_id=tmsg.user_uid, user_issue=issue_id) except Exception as exc: logger.error(f'Error in creating new key {exc}') telegram.send_message(token, tmsg.chat_id, globalvars.lang.text('MSG_ERROR')) return None if not new_key: telegram.send_message(token, tmsg.chat_id, globalvars.lang.text('MSG_ERROR')) else: awsurl = (CONFIG['OUTLINE_AWS_URL'].format( urllib.parse.quote(new_key))) telegram.send_message( token, tmsg.chat_id, globalvars.lang.text('MSG_NEW_KEY_A').format(awsurl), parse='MARKDOWN') telegram.send_message(token, tmsg.chat_id, globalvars.lang.text('MSG_NEW_KEY_B'), parse='MARKDOWN') telegram.send_message(token, tmsg.chat_id, new_key)
def set_user_telegram(): """Show user""" user = session.get('auth_user') result = tlg.get_chat_id(TELEGRAM_TOKEN, user['chat_token']) user_to_update = User.query.filter_by(id = user['id']).first() user_to_update.chat_id = result db.session.commit() tlg.send_message(user_to_update.chat_id, TELEGRAM_TOKEN, "Token activated") return redirect(url_for('get_user'))
def run(date): utc_date_str = datetime.strftime(date, '%m/%d/%Y %H:%M:%S %p (UTC)') message = utc_date_str + '\n' for exchange in exchanges: api = getattr(ccxt, exchange)() last_price = round(api.fetch_ticker(symbol='BTC/USD')['last'], 2) message += exchange.capitalize() + ': $' + str(last_price) + '\n' telegram.send_message(file=__file__, message=message)
def add_remainder(self, user, text): remainder.remove_job(user) tokens = text.split(' ') delta = datetime.timedelta() if len(tokens) >= 2: tokens = tokens[1].replace(' ', '').split(':') hours = int(tokens[0]) minutes = int(tokens[1]) delta = datetime.timedelta(hours=hours, minutes=minutes) remainder.add_job(user, datetime.datetime.utcnow() + delta) telegram.send_message(user['chat_id'], "Successfully set. Nearest at %s" % (datetime.datetime.now() + delta,))
def langs_ask(self, user, text): ans = requests.get('https://translate.yandex.net/api/v1.5/tr.json/getLangs', {'key': self.settings.translate_yandex['token']}) lang_list = ans.json()['dirs'] if text not in lang_list: telegram.send_message(user['chat_id'], "Please, choose any of this:\n" + "\n".join(lang_list)) else: telegram.send_message(user['chat_id'], "\"%s\" have successfully chosen" % (text,)) user['state'] = States.idle user['foreign'] = text[0:2] user['native'] = text[3:5]
def irc_to_telegram(): irc_message_data = '' irc.connect(sv_address, sv_port, us_pass, us_nick) while 1: irc_message_data = irc.listen(irc_message_data) gen_msg = GENERAL_MSG_REGEX.search(str(irc_message_data)) if gen_msg: msg_user, msg_source, msg_text = gen_msg.group(1), gen_msg.group(2), gen_msg.group(3) if msg_source == (f'#{irc_channel}'): telegram.send_message(telegram_group_id, f'[{msg_user}]: {msg_text}')
def monitor(self): self.check_is_top21() self.check_latency() if self.bp.is_top21 is False: msg = 'bp with name %s NOT FOUND!!! @ %s' % (BP_NAME, get_current_time()) print("in is top21 ", get_current_time()) send_message(msg) if self.bp.is_new_top21 is True: msg = 'Congratulations! %s become the new top 21 ! @ %s' % ( BP_NAME, get_current_time()) print('in is new top21', get_current_time()) send_message(msg) call() if self.bp.is_top21 is True: self.notify_count += 1 if self.notify_count % 64 == 0: if self.check_is_producing(): msg = '%s in good condition :) @%s' % (BP_NAME, get_current_time()) print('produing....', get_current_time()) self.notify_count = 0 send_message(msg) else: msg = '%s DOWN :( @%s' % (BP_NAME, get_current_time()) print('down...', get_current_time()) send_message(msg) call()
def check_signal(self): try: ebusd.check_signal() except ValueError as e: self.set_state(EbusClientState.no_signal) if str(e) == ebusd.EbusdErr.RESULT_ERR_NO_SIGNAL.value: self.print_no_signal += 1 if self.print_no_signal > EBUS_LOGGER_NO_SIGNAL_TO_SEC: self.print_no_signal = 0 self.logger.error(str(e)) self.print_no_signal_telegram += 1 if self.print_no_signal_telegram > EBUS_TELEGRAM_NO_SIGNAL_TO_SEC: self.print_no_signal_telegram = 0 telegram.send_message(str(e)) raise e
def main(): init() while True: try: chat_id, message = telegram.get_message() output = handler(chat_id, message) telegram.send_message(chat_id, output) except TimeoutError: continue except telegram.TelegramError as e: logging.error(f"Exception occured\n{e}") continue except KeyboardInterrupt: save() exit()
def run(chrome): prev_amt = pd.read_csv('tether.csv'').iloc[0, 0] chrome.get(url) table = chrome.load('ul[@class="result-list"]/div/div[1]') for element in table: amt, date = find_amt_date(element) if amt == prev_amt: break message = 'ALERT: ' + amt + ' USDT sent on ' + date telegram.send_message(file=__file__, message=message) most_recent_amt, _ = find_amt_date(table[0]) pd.DataFrame(data=[most_recent_amt], columns=['Tether Printed']).to_csv(CSV_FILE,index=False)
def check_datetime(self): time = self.read_0('Time') date = self.read_0('Date') b7v_dt = datetime.datetime.strptime(date + ' ' + time, '%d.%m.%Y %H:%M:%S').replace(microsecond=0) dt = datetime.datetime.now().replace(microsecond=0) diff_sec = abs((b7v_dt - dt).total_seconds()) if diff_sec > 60: self.write_0('Date ' + dt.strftime('%d.%m.%Y')) self.write_0('Time ' + dt.strftime('%H:%M:%S')) msg = 'VRC700: adjusted system date/time: was ' + str(b7v_dt) + \ ' set to ' + str(dt) self.logger.error(msg) telegram.send_message(msg) telegram.send_message('VRC700: ' + str(b7v_dt))
def main(settings): download_dir = settings.download_path if not os.path.isdir(download_dir): os.mkdir(download_dir) with ftpclient.openftp(settings.ftp_server) as ftp: for keyword in settings.search_keywords: for class_ in scrapper.classes: site_scrapper = class_(ftp, settings.telegram, download_dir) try: site_scrapper.search(keyword) except Exception as ex: token: str = settings.telegram.token chat_id: str = settings.telegram.chat_id telegram.send_message( token, chat_id, f'exception={traceback.format_exc()}')
def record_mined_cet(): if records['predict_cet'] == 0: return cur_hour = time.strftime("%Y-%m-%d %H", time.localtime()) item = '%s mined %0.3f CET\r\n' % (cur_hour, records['predict_cet']) logging.info(item) if config.telegram_notify: send_message(item) with open('records.txt', 'a+') as f: f.write(item) records['predict_cet'] = 0
def app(): top_posts = get_posts() buffer = db.get_buffer() buffer_ids = [d['id'] for d in buffer] print(f'Buffer ID\'s: {buffer_ids}. Length {len(buffer_ids)}') new_posts = [] score = int(environ["reddit_score"]) for post in top_posts: if post.score >= score and post.id not in buffer_ids: print( f'The post {post.id} is valid for publishing ({post.score} upvotes, {score} needed)' ) tg.send_message(post) new_posts.append(to_buffer_format(post)) db.put_to_archive(post) if len(new_posts) > 0: db.put_in_buffer(new_posts)
def balance_cost(): #return if records['money_fees'] < 0.0001 or records['goods_fees'] < 0.0001: logging.info('no need to balance the cost') return goods_markets = config.market logging.info('need buy %s: %0.3f' % (config.goods, records['goods_fees'])) data = _private_api.get_ticker(goods_markets) data = data['data'] price = float(data['ticker']['sell']) amount = records['goods_fees'] logging.info('buy %0.3f at %f %s' % (amount, price, goods_markets)) _private_api.buy(amount, price, goods_markets) records['goods_fees'] = 0 _money_cast_buy_goods = amount * price money_markets = 'CET' + config.money logging.info('need buy %s: %0.3f' % (config.money, records['money_fees'])) data = _private_api.get_ticker(money_markets) data = data['data'] price = float(data['ticker']['buy']) amount = (records['money_fees'] + _money_cast_buy_goods) / price logging.info('sell %0.3f at %f %s' % (amount, price, money_markets)) _private_api.sell(amount, price, money_markets) records['money_fees'] = 0 cur_hour = time.strftime("%Y-%m-%d %H", time.localtime()) item = '%s mined %0.3f CET\r\n' % (cur_hour, records['predict_cet']) logging.info(item) if config.telegram_notify: send_message(item) with open('records.txt', 'a+') as f: f.write(item) records['predict_cet'] = 0
def remove(self, user, text): if user['train']['type'] != 0: for w in user['words']: if w == user['train']['word']: user['words'].remove(w) str_out = "%s - %s" % (w['en'], w['ru']) telegram.send_message(user['chat_id'], "Deleted:\n%s" % (str_out,)) train.do_train(user, text) else: tokens = text.split(" ") if len(tokens) > 1: cnt = int(tokens[1]) if cnt > 0: cnt -= 1 else: cnt = -1 str_out = "%s - %s" % (user['words'][cnt]['en'], user['words'][cnt]['ru']) del user['words'][cnt] telegram.send_message(user['chat_id'], "Word with index %s removed\n%s" % (cnt, str_out))
def get_updates(self): try: messages = telegram.get_updates(self.params['offset']) for u in messages: if 'message' in u and 'text' in u['message']: if u['update_id'] < self.params['offset']: print('Error') else: chat_id = u['message']['chat']['id'] text = u['message']['text'] self.params['offset'] = max(self.params['offset'], u['update_id'] + 1) try: self.parse_action(chat_id, text) except: logging.error('Error! (%s, %s)' % (chat_id, text)) logging.error(traceback.print_exc()) telegram.send_message(chat_id, 'An error occurred!') except: logging.error('Get updates error!') logging.error(traceback.print_exc()) self.db.meta.save(self.params)
def main(): config_file = parser().file_name config = read_config(config_file) # config = read_config(os.getcwd() + '\\config.yaml') bot_api_key = get_API_key(config) bot_chat_id = get_bot_chat_id(config) logger.debug(bot_chat_id) request = create_request() if check_HTTP_status(request): jobs = get_jobs(request) last_run = get_last_run_timestamp() new_jobs = get_new_jobs(jobs, last_run) if new_jobs: send_message(new_jobs, bot_api_key, bot_chat_id) # for job in new_jobs: # print(job) else: print('No new jobs!') send_message(new_jobs, bot_api_key, bot_chat_id) set_last_run_timestamp() logger.info(f'Successfully ran at {get_last_run_timestamp()}')
def check_latency(self): self.latency_count += 1 if self.latency_count % 30 == 0: # call every one minute latency = self.lr.get_latency() if latency != -1: if 2000 < latency <= 4000: msg = "bp %s's latency %s ms is too high !!! @ %s" % ( BP_NAME, latency, get_current_time()) print(msg) send_message(msg) self.latency_count = 0 elif latency > 4000: msg = "bp %s is stucking now. The latency is %s ms !!! @ %s" % ( BP_NAME, latency, get_current_time()) print(msg) send_message(msg) self.latency_count = 0 call() elif 0 < latency <= 2000: msg = "bp %s has normal latency %s ms!!! @ %s" % ( BP_NAME, latency, get_current_time()) print(msg) send_message(msg) self.latency_count = 0 else: self.latency_count = 0
def record_mined_cet(): if records['predict_cet'] == 0: return cur_hour = time.strftime("%Y-%m-%d %H", time.localtime()) item = '%s mined %0.3f CET\r\n' % (cur_hour, float(records['predict_cet'])) logging.info(send_message(item)) with open('records.txt', 'a+') as f: f.write(item) records['predict_cet'] = 0
def process(): global temperature global timestamp temperature = {} timestamp = None try: temperature = get_sinoptik() except (IndexError, ValueError): return if not temperature: return timestamp = time.time() logger.debug(temperature) hour_idx = get_sinoptik_cur_hour_index(timestamp) # store to the database try: if hour_idx < 0: t_feels_like = '' else: t_feels_like = temperature['forecast_feels_like_hourly'][hour_idx] values = { 'T_sinoptik': temperature['t_now'], 'T_sinoptik_feels_like': t_feels_like } database.store_weather(values) telegram.send_message('Toutside ' + temperature['t_now'] + ' feels like ' + t_feels_like) except (ValueError, IndexError) as e: logger.error(str(e))
def add_word(self, user, string): baseurl = 'https://translate.yandex.net/api/v1.5/tr.json/translate' # string = re.sub(r'[^A-Za-z\s]', '', string) # string = re.sub(r'\Wk+', ' ', string) string = string.lower() if len(string) == 0: telegram.send_message(user['chat_id'], "Wrong word") return if 'foreign' not in user: user['foreign'] = 'en' user['native'] = 'ru' if user['foreign'] == 'en': string = self.correct(string) if env != 'debug': string = self.wnl.lemmatize(string) string = string[0].upper() + string[1:] direction = '%s-%s' % (user['foreign'], user['native']) transtaltion = requests.get(baseurl, { 'key': self.settings.translate_yandex['token'], 'lang': direction, 'text': string }) out_word = transtaltion.json()['text'][0] already_has = False for w in user['words']: already_has |= w["en"] == string if not already_has: user['words'].append({"en": string, "ru": out_word, "stage": study_settings.min_stage, "expiration_date": datetime.datetime.utcnow() + study_settings.stages[1], "creation_date": datetime.datetime.utcnow()}) self.users.save(user) telegram.send_message(user['chat_id'], "Word added\n%s - %s" % (string, out_word)) else: telegram.send_message(user['chat_id'], "Already exist!\n%s - %s" % (string, out_word))
def help(self, user, text): telegram.send_message(user['chat_id'], self.help_text)
def main(): global records welcome = 'CoinexMiner Started!' logging.info(welcome) if config.telegram_notify: send_message(welcome) try: records = pickle.load(open('cache.data', 'rb')) logging.info(records) except Exception as e: logging.info('no cache file found.') get_self_cet_prediction() importlib.reload(config) while True: #runtime load config: good for runtime adjust settings #importlib.reload(config) try: update_balance() except Exception as e: logging.info('update_balance failed try again 1') time.sleep(10) try: update_balance() except Exception as e: logging.info('update_balance failed try again 2') time.sleep(5 * 60) update_balance() if random.random() < 0.2: try: get_self_cet_prediction() except Exception as e: logging.info('get_self_cet_prediction: ' + str(e)) cur_time = time.time() since_balance_cost_time = (cur_time - records['balance_cost_time']) / 60 logging.info('%0.2f minute ago have executed balance fee cost' % since_balance_cost_time) if since_balance_cost_time > 60: logging.info('balance the fee cost. time beyond 1 hour') balance_cost() records['balance_cost_time'] = cur_time if need_pause(): logging.info('need_pause mine too much') pickle.dump(records, open('cache.data', 'wb')) cur_min = time.gmtime().tm_min if cur_min > 10: #time.sleep(float(60-cur_min)*60) time.sleep(1 * 60) else: time.sleep(5) continue try: records['variance'] = calculate_variance(_private_api) except json.decoder.JSONDecodeError as e: logging.error('calculate_variance json.decoder.JSONDecodeError') logging.info('wave ratio: %0.3f%%' % records['variance']) if records['variance'] < config.wave_ratio: logging.info('no fluctuation') status = digging() pickle.dump(records, open('cache.data', 'wb')) time.sleep(3)
continue try: records['variance'] = calculate_variance(_private_api) except json.decoder.JSONDecodeError as e: logging.error('calculate_variance json.decoder.JSONDecodeError') logging.info('wave ratio: %0.3f%%' % records['variance']) if records['variance'] < config.wave_ratio: logging.info('no fluctuation') status = digging() pickle.dump(records, open('cache.data', 'wb')) time.sleep(3) if __name__ == "__main__": while True: try: main() except Exception as e: logging.error(str(e)) if config.telegram_notify: send_message('CoinexMiner: ' + str(e) + ', restarting in 1 min') time.sleep(60)
def send_remainder(): telegram.send_message(chat_id, "Hey! It is time to learn") logging.debug("Added job succeed. Chat id: %s" % (chat_id,))
def get_cpu_temperature(): with open("/sys/class/thermal/thermal_zone0/temp", "r") as f: temp = f.read() temp = int(temp) / 1000.0 return temp # Tuning factor for compensation. Decrease this number to adjust the # temperature down, and increase to adjust up factor = 2.25 cpu_temps = [get_cpu_temperature()] * 5 last_max = datetime.now() TEN_MINUTES = 10 * 60 while True: cpu_temp = get_cpu_temperature() # Smooth out with some averaging to decrease jitter cpu_temps = cpu_temps[1:] + [cpu_temp] avg_cpu_temp = sum(cpu_temps) / float(len(cpu_temps)) raw_temp = bme280.get_temperature() comp_temp = raw_temp - ((avg_cpu_temp - raw_temp) / factor) if comp_temp > 25: duration = datetime.now() - last_max if duration.total_seconds() > TEN_MINUTES: telegram.send_message("ALERT:{:05.2f} C".format(comp_temp)) logging.info("Sent alert") last_max = datetime.now() logging.info("Compensated temperature: {:05.2f} *C".format(comp_temp)) time.sleep(1.0)
def get_list_word(self, user, text): str_out = "\n".join(["%s: (%s) %s - %s" % (i + 1, w['stage'], w['en'], w['ru']) for i, w in zip(range(10 ** 10), user['words'])]) telegram.send_message(user['chat_id'], str_out)
def start(self, user, text): telegram.send_message(user['chat_id'], self.welcome_text) user['state'] = States.langs_asked
if need_pause(): logging.info('need_pause mine too much') time.sleep(5) pickle.dump(records, open('cache.data', 'wb')) continue try: records['variance'] = calculate_variance(_private_api) except json.decoder.JSONDecodeError as e: logging.error('calculate_variance json.decoder.JSONDecodeError') logging.info('wave ratio: %0.3f%%' % records['variance']) if records['variance'] < config.wave_ratio: logging.info('no fluctuation') status = digging() pickle.dump(records, open('cache.data', 'wb')) time.sleep(3) if __name__ == "__main__": try: main() except Exception as e: logging.error(str(e)) if config.telegram_notify: send_message('CoinexMiner: ' + str(e))
def callback(msg): user=bot.users[msg.actor].get_property("name") message=msg.message #print(user+":"+message) telegram.send_message(user+":"+message)
def take_leads(driver): time.sleep(5); driver.get(datas.app_lead); driver.implicitly_wait(10); try: driver.switch_to.frame(driver.find_element_by_xpath('//*[@class="app-frame"]')); driver.switch_to.frame(driver.find_element_by_xpath('//*[@class="partner-application-install-select-country-iframe"]')); except: None; #take rows with leads all_leads_string = driver.find_elements_by_class_name('main-grid-row.main-grid-row-body'); #print('Всего заявок:',len(all_leads_string)); list_of_leads = []; for row in all_leads_string: count_column = 1; columns = row.find_elements_by_class_name('main-grid-cell-content'); #print('Всего столбцов', len(columns)) #take all data wrom lead: #if can't take we have 7 columns if len(columns) == 7: num_string = 1; #we pass taken leads: continue; #if can take we have 8 columns: else: num_string = 2; #take main parametres in each row for column in columns: #take description apparantly - descr is first num: if count_column == num_string: description = column.find_element_by_class_name('partner-application-b24-list-description-inner.js-description-inner'); #print('description:',description.text) #take time - when we tooke lead?: if count_column == num_string+1: time_take = column.text; #print('time:',time_take) #take city: if count_column == num_string+2: city = column.text; #print('city:',city) #take can we take'Сделка в CRM' or 'ВЗЯТЬ ЗАЯВКУ': if count_column == num_string+4: can_take = column.text; #print(can_take); #print('cn we take:',can_take) count_column += 1; if num_string == 2: #search keys: for i in datas.keys: #compaire description if i in description.text.lower(): #compaire city for i in datas.cities: if i in city.lower(): #does we take? if 'ВЗЯТЬ ЗАЯВКУ' in can_take: take = row.find_element_by_class_name("partner-application-b24-list-item-submit-link.js-partner-submit-application"); driver.execute_script("arguments[0].scrollIntoView(true);", take); take.click(); print('\n\n\nWe take lead\n' + city + '\n\n'); #break; #print(str(count_column) + '. ' + column.text); try: telegram.send_message('Мы только что взяли заявку:\n' + 'Город:\n' + city + '\n----\nОписание:\n' + description.text); except: telegram.send_mistake();
def main(): global last_event_counter global event_counter mode="debug" one_minute=60000/1000#seconds one_second=one_minute/60 berry =None if os.getuid() != 0: print("This program is not run as sudo or elevated this it will not work") exit() if len(sys.argv) == 2: if sys.argv[1] == "--release" or sys.argv[1] == "--debug": mode=sys.argv[1][2:]#cut -- else: print(sys.argv[1]+" is not a valid mode (--release or --debug)") exit() telegram.init(mode) #mumble_chat.init() print("start mumble_bot mode="+mode) delay=one_second#init delay cert_exp="" ip="" while True: time.sleep(delay);#wait in the release version online_users= read_Online_Users()# set event_counter registeredUsers= read_Registered_Users() one_user_online=False #check if a user is loged in for user in online_users: #print(user+" "+str(online_users[user])) if online_users[user].event_counter%2!=0: one_user_online=True #write to std out or whatsapp if last_event_counter != event_counter and len(online_users)!=0: #there is a user stat change message="" delay=one_minute*0.5;#wait with the next check 30 sec #***************************************************** #********** telegram part**************************** #***************************************************** #iterate over online users for user in online_users: if user in registeredUsers.keys():#user is registered #compute message if online_users[user].event_counter % 2 != 0: message+=user+"\t"+ u'\U00002705'+"\n"#online else: message+=user+"\t"+ u'\U0000274C'+"\n"#offline if message!="":#a registered user is online message="*****************\nPbtH-Mumble v2.1\n*****************\n"+message#add message to whats app command #print(message.encode("utf-8").expandtabs()) telegram.send_message(message.encode("utf-8").expandtabs(16)) last_event_counter = event_counter;#reset event counter #***************************************************** #********** c-berry part****************************** #***************************************************** if berry==None: berry=cberry.Cberry() berry.turn_screen_on() cert_exp=get_cert_validity() ip=getIP() berry.print_on_screen(online_users,ip,cert_exp)#update screen in any case #write to display if(one_user_online==False):#there aren't online users berry.turn_screen_off() berry=None else: delay=one_second#reset delay
def reask_langs(self, user, text): telegram.send_message(user['chat_id'], """ Now choose your native and foreign languages. Example: "en-ru" (en is foreign and ru is native) """) user['state'] = States.langs_asked
def remove_remainder(self, user, text): remainder.remove_job(user) telegram.send_message(user['chat_id'], "Removed")
# Dismissing Prompt wait = WebDriverWait(browser, 300) wait.until(EC.alert_is_present()) alert_obj = browser.switch_to.alert alert_obj.accept() wait.until(EC.visibility_of_element_located((By.CLASS_NAME, "btn"))) # 0 refers to first slot, 1 refers to second slot, and so on... slots = browser.find_elements_by_name('slot') # Parse slot information times=[] for slot in slots: td = slot.find_element_by_xpath('..') text = td.get_attribute("onmouseover") parts = text.split(",") session = parts[3] session = session.replace('"', '') date = parts[2] start = parts[4] end = parts[5] current = date + ", " + start + "-" + end + ", session: " + session current = current.strip().replace('"', '') # Example: 03/02/2021 (Wed), 0730-09:10, session: 1 times.append(current) message = 'No slots available :(\n' if len(times) == 0 else "Found slots: \n"+'\n'.join(times) # Send to telegram and print in console telegram.send_message(message) print(message) time.sleep(60 * 5) # 5min: 60s * 5
def about(self, user, text): telegram.send_message(user['chat_id'], self.about_text)