def send_data_to_telegram(): direction_values = ['low', 'high'] interval_values = ['7d', '24h'] direction = '' interval = 0 new_value = '' while direction not in direction_values: direction = input( 'change values for increase or decrease? "low" or "high" ') if direction in direction_values: break print('wrong input. please select either "low" or "high"') while interval not in interval_values: interval = input('change values for what interval? "7d" or "24h" ') if interval in interval_values: break print('wrong input. please select either "7d" or "24h"') while type(new_value) != int: try: new_value = int(input('new value? 7/24 ')) except: print('wrong input. please select select a number') telegram_send.send(messages=[ f'Setting new threshold for {interval} interval for {direction} direction: {str(new_value)}' ]) get_db().execute( f'UPDATE config SET {direction}_{interval} = {str(new_value)} WHERE id = 1' ) get_db().commit()
def custom(bot, update): driver = webdriver.Chrome() driver.get( "https://zh.wikipedia.org/zh-tw/%E9%98%B2%E5%BD%88%E5%B0%91%E5%B9%B4%E5%9C%98" ) cond = driver.find_elements_by_tag_name('img') cond[0].get_attribute('src') def url_to_file(url, filename): result = requests.get(url) result.raise_for_status() with open(filename, 'wb') as FILE: for chunk in result.iter_content(102400): FILE.write(chunk) temp = [] #建制空陣列 for i, img in enumerate(cond): #找出全部 subname = img.get_attribute('src').split('.')[-1] if (subname == 'jpg'): url_to_file( img.get_attribute('src'), 'C:/Users/LOVESS/Desktop/bts/{}.{}'.format(i + 1, subname)) temp.append(i + 1) print(temp) num = random.choice(temp) print(num) with open("C:/Users/LOVESS/Desktop/bts/{}.jpg".format(num), "rb") as f: #要讓他有隨機的 telegram_send.send(images=[f])
def sendToChannel(newNotice): """ Sends the new notice to the channel using telegram bot """ newNoticeStr = f'Title:{newNotice["title"]}\nLink:{newNotice["link"]}' telegram_send.send(messages=[newNoticeStr], conf="telegram-send.conf") return 200
def report(self, video_to_send, video_dim, state, camera_name): """ Sends a message containing the `state`, the `camera_name` that detected it and the `video_to_send` with dimensions `vid_dim`x`vid_dim` via Telegram. :param video_to_send: A queue containing the frames of the fall / recover :param video_dim: The dimension of the output video :param state: A string with the state obtained: "Fall" / "Nothing" / "Recover" :param camera_name: A descriptive camera name """ file_video_name = "{}{}.mp4".format(self.video_name, camera_name) video = cv2.VideoWriter(file_video_name, cv2.VideoWriter_fourcc(*'mp4v'), self.frame_rate, (video_dim, video_dim)) for frame in video_to_send: video.write(frame) video.release() alert_icon = "⚠" if state == "Recover": alert_icon = "👍🏼" message = "{}{} detected{}: {}".format(alert_icon, state, camera_name, alert_icon) telegram_send.send(messages=[message]) telegram_send.send(captions=[message], videos=[open(file_video_name, 'rb')])
def log_in(email_address, pass_word): logging.info(msg=f'Logging in {email_address}...') telegram_send.send(messages=[f'Logging in {email_address}...']) browser.get('https://login.live.com/') # wait for login form and enter email wait_until_clickable(By.NAME, 'loginfmt', 10) send_key_by_name('loginfmt', email_address) send_key_by_name('loginfmt', Keys.RETURN) logging.debug(msg='Sent Email Address.') if not parser.use_authenticator: # wait for password form and enter password wait_until_clickable(By.NAME, 'passwd', 10) send_key_by_name('passwd', pass_word) logging.debug(msg='Sent Password.') # wait for 'sign in' button to be clickable and sign in wait_until_visible(By.NAME, 'passwd', 10) send_key_by_name('passwd', Keys.RETURN) wait_until_visible(By.ID, 'idSIButton9', 10) click_by_id('idSIButton9') # Passwords only require the standard delay wait_until_visible(By.CSS_SELECTOR, 'div#navs > div > div > div > a', 20) else: # If using mobile 2FA, add a longer delay for sign in approval wait_until_visible(By.CSS_SELECTOR, 'div#navs > div > div > div > a', 300) time.sleep(0.5)
def send_email (event_id, to_addr, message): global LAST_MESSAGES last_send_time, last_send_message = LAST_MESSAGES.get(event_id, (0,"")) if last_send_message == message: if time.time() - last_send_time < 60*60: # the same message was sent within an hour return LAST_MESSAGES[event_id] = (time.time(), message) print("send email {}:{}".format(event_id, message)) smtp_server = "smtp.gmail.com" port = 587 # For starttls sender_email = "*****@*****.**" with open("example.txt", "r") as inp: text_cut = inp.read()[1024:1034] context = ssl.create_default_context() try: server = smtplib.SMTP(smtp_server, port) server.starttls(context=context) # Secure the connection server.login(sender_email, text_cut) server.sendmail(sender_email, to_addr, message) except Exception as e: print(e) finally: server.quit() try: telegram_send.send(messages=[message]) except Exception as e: print(e)
def send_success(page: PlaywrightPage, msg: str): telegram_send.send(messages=[msg]) with tempfile.TemporaryFile("r+b") as fp: encoded_img = page.screenshot(type="png") fp.write(encoded_img) fp.seek(0, 0) telegram_send.send(images=[fp])
def send_message_via_telegram(message: str, image_path: str = None) -> None: """ Sends a message as TrainingFather. Example usage: - send_message_via_telegram("Training father is speaking to you!") - send_message_via_telegram("Only the *bold* use _italics_") Each machine that needs to send a message, should run the following (from command-line): telegram-send --configure # Connect to the bot, e.g. Alex12345Bot, by adding its Access Token # Connect your user-account to the bot and enter the password :param image_path: A path to a file on the disk that should optionally be sent along with the message :param message: The message to be sent in markdown formatting """ try: if image_path is not None: with open(image_path, "rb") as f: telegram_send.send([message], parse_mode="text", images=[f]) else: telegram_send.send([message], parse_mode="text") except Exception as exception: print("Error while sending notification via telegram: {0}".format( str(exception))) traceback.print_exc()
def parser(str): message = str start = message.find('<eventParameters') end = message.find('</eventParameters>') text = '<?xml version="1.0" encoding="UTF-8"?>' + message[start:end] + '</eventParameters>' print('text', text) if text != '</q:quakeml>': myroot = ET.fromstring(text) for x in myroot: if x.tag == 'event': event = x[0].text print(event) elif x.tag == 'origin': time = x[0][0].text print(time) longitude = x[1][0].text longitude_uncert = x[1][1].text latitude = x[2][0].text latitude_uncert = x[2][1].text depth = x[3][0].text depth_uncert = x[3][1].text elif x.tag == 'magnitude': magnitude = x[0][0].text magnitude_lower_uncert = x[0][1].text magnitude_upper_uncert = x[0][2].text print(magnitude, magnitude_lower_uncert, magnitude_upper_uncert) elif x.tag == 'pick': attribs = json.dumps(x.attrib) print(attribs) # station_code = x[1][0].tag # print(station_code) message_text = "time: " + time + "\nlongitude: " + longitude + "\nlatitude: " + latitude + "\ndepth: " + depth + "\nmagnitude: " + magnitude + '\nattributes: ' + attribs print('tags', myroot.tag) telegram_send.send(messages=[message_text])
def log_message(message): logging.info(message) telegram_send.send(conf='conf/master.conf', messages=[ str(datetime.now().strftime('%m/%d/%Y %H:%M:%S')) + ' - ' + message ])
def getAvailability(location): try: # interpolate location with base url url = "https://www.auchandrive.lu/drive/{0}/".format(location2Url[location]) print("url of {0}:".format(location), url) # get page using request page = requests.get(url, verify=False) # get parsed content parsed = BeautifulSoup(page.text, "html.parser") # get next slot slotInfo = parsed.find("div", {"class": ["info-drive_next-slot"]}) # get innertext of paragraph as string fullStatus = str(slotInfo.text) # process innertext status = fullStatus[28:] # check for noSlotKeyword in status if noSlotKeyword in status: available = False else: available = status except: available = None telegram_send.send(messages=["An error has occurred getting the availability of {0}".format(location)]) print("\n") return available
def send_quake_message(relevantquakes, tgconfig='path/to/tg.cdf', memorypath='', debug=False): for quake in relevantquakes: print("Creating message:") quakemsg = "{} at *{}* UTC\n".format(quake[0].split()[0], quake[0].split()[1]) quakemsg += "{} with magnitude *{}*\n{}\n".format( quake[8], quake[4], quake[7].replace("REGION", "")) quakemsg += "Latitude: {}°\n".format(quake[1]) quakemsg += "Longitude: {}°\n".format(quake[2]) quakemsg += "Depth: {}km".format(quake[3]) print(quakemsg) zoom = 9 maplink = "[Show map](https://maps.google.com/maps/?q={},{}&ll={},{}&z={})\n".format( quake[1], quake[2], quake[1], quake[2], zoom) mapling = "Further info: [ZAMG/ConradObs](https://www.zamg.ac.at/cms/de/geophysik/erdbeben/aktuelle-erdbeben/karten-und-listen/)" print(maplink) print("----------------------------\n") # Sending the data to the bot if not debug: print("Sending message to Telegram") telegram_send.send(messages=[quakemsg + "\n" + maplink], conf=tgconfig, parse_mode="markdown") print(" -> sending done ... adding to memory") np.save(memorypath, quake) print(" -> Done") else: print(" DEBUG selected - not sending and saving anything") print(" -> projected telegram configuration: {}".format(tgconfig))
def wait_until_clickable(by_, selector, time_to_wait=10): """ Waits 5 seconds for element to be clickable :param by_: BY module args to pick a selector :param selector: string of xpath, css_selector or other :param time_to_wait: Int time to wait :return: None """ try: WebDriverWait(browser, time_to_wait).until( ec.element_to_be_clickable((by_, selector))) except TimeoutException: logging.exception( msg=f'---> {selector} element Not clickable - Timeout Exception', exc_info=False) telegram_send.send(messages=[ f'---> {selector} element Not clickable - Timeout Exception' ]) screenshot(selector) except UnexpectedAlertPresentException: # FIXME browser.switch_to.alert.dismiss() # logging.exception(msg=f'---> {selector} element Not Visible - Unexpected Alert Exception', exc_info=False) # telegram_send.send(messages=[f'---> {selector} element Not Visible - Unexpected Alert Exception', exc_info=False]) # screenshot(selector) # browser.refresh() except WebDriverException: logging.exception(msg=f'---> Webdriver Error for {selector} object') telegram_send.send( messages=[f'---> Webdriver Error for {selector} object']) screenshot(selector)
def notify(title, message, retcode=None): """Sends message over Telegram using telegram-send, title is ignored.""" if not path.exists(config_file): if not path.exists(config_dir): makedirs(config_dir) print("Follow the instructions to configure the Telegram backend.\n") configure(config_file) send(messages=[message], conf=config_file)
def message_telegram(msg): msg = str(msg) try: telegram_send.send(messages=[msg]) except requests.exceptions.RequestException as e: logging.error('Telegram reachability issue : ' + str(e)) print('No Telegram:-->\t' + msg) return
def sendTelegram(): now = datetime.now() current_time = now.strftime("%H:%M:%S") dt_string = now.strftime("%d/%m/%Y") telegram_send.send(messages=[ "Motion detected in your house!\n\nDate :" + dt_string + "\n" + "Time :" + current_time + "\n\nTake action immediately!" ])
def notify_telegram(self): listing = traceback.format_exception(self.type_, self.value, self.traceback) del listing[1] final_msg = "<b>Error at line {} in file {}</b> \n".format( self.traceback.tb_lineno, sys.argv[0]) final_msg += "".join(listing) telegram_send.send(messages=[final_msg], parse_mode='html')
def bad_joker(process_string): process = Popen(process_string.split(" "), stderr=PIPE, stdout=PIPE) (output, err) = process.communicate() message = _generate_default_joke() exit_code = process.wait() if exit_code == 1: message = _generate_joke(err.decode("utf-8")) telegram_send.send([message])
def api_sell_crypto(crypto_data, name): # Check if there are any buy orders ongoing and cancel them try: orders = k.get_open_orders(symbol=name) if (len(orders) > 0): for order in orders: try: cancel = k.cancel_order(symbol=name, orderId=order['orderId']) telegram_send.send(messages=['B ', cancel]) orders = k.get_open_orders(symbol=name) except BinanceAPIException as e: print('BinanceAPIException', e) report_go('ERROR' + str(e)) except BinanceOrderException as e: print('BinanceOrderException', e) report_go('ERROR' + str(e)) except BinanceAPIException as e: print('BinanceAPIException', e) report_go('ERROR' + str(e)) except BinanceOrderException as e: print('BinanceOrderException', e) report_go('ERROR' + str(e)) # Sell crypto balance try: balance = api_get_balance() price = api_get_ticker(name) if (float(balance[name][0]) > 0.0 and float(balance[name][1]) == 0.0): amount = rounddown(float(balance[name][0]), 6) try: trorder = k.create_order(symbol=name, side='SELL', type='MARKET', quantity=str(amount)) tlmsg = trorder['side'] + '-' + trorder[ 'symbol'] + '\n' + trorder['fills'][0]['qty'] + ' ' + name[ 0:3] + '\n' + trorder[ 'cummulativeQuoteQty'] + ' EUR' + '\n' + trorder[ 'fills'][0]['commission'] + ' ' + trorder[ 'fills'][0]['commissionAsset'] #telegram_send.send(messages=['B ',tlmsg]) report_go(tlmsg) print() print('SELL', amount, name, 'at', price, 'for', amount * price) except BinanceAPIException as e: print('BinanceAPIException', e) #telegram_send.send(messages=['B ',e]) report_go('ERROR' + str(e)) except BinanceOrderException as e: print('BinanceOrderException', e) #telegram_send.send(messages=['B ',e]) report_go('ERROR' + str(e)) except BinanceAPIException as e: print('BinanceAPIException', e) except BinanceOrderException as e: print('BinanceOrderException', e)
def send_message_if_needed(results, filepath, labels_to_trigger): results_filtered = [res for res in results if res[0] in labels_to_trigger] if results_filtered: print("Triggering for %s." % (labels_to_trigger)) serializable_results = [str(res) for res in results_filtered] telegram_send.send(messages=["Found for file at %s" % filepath]) telegram_send.send(messages=[serializable_results]) else: print("no trigger found.")
def main(): old_html = None #urllib.request.urlopen(URL).read() while True: time.sleep(15) new_html = urllib.request.urlopen(URL).read() if new_html != old_html: telegram_send.send(messages=('Esiti disponibili ' + URL, )) old_html = new_html
def tgsend(): for i in range(len(mdf)) : a = mdf.loc[i, "book_id"] b = mdf.loc[i, "country"] c = mdf.loc[i, "previous_value"] d = mdf.loc[i, "current_value"] e = mdf.loc[i, "m_value"] f = mdf.loc[i, "when_start"] telegram_send.send(messages=["####### Start ####### \n BookId : {}\n Country : {} \n PreviousValue : {}\n CurrentValue : {} \n MarginValue : {} \n WhenStart : {} \n ####### End ####### ".format(a,b,c,d,e,f)])
def __trade__(self, time, symbol, quantity): order = {"instrument": symbol, "units": quantity} resp = self.ctx.order.market(self.account_id, **order) if resp.status == 200 and hasattr(resp, "orderFillTransaction"): send([ f'{self.account_id} submited trade ID: {str(resp.get("lastTransactionID"))}' ]) self.save_record(time, symbol, resp.get("orderFillTransaction").price, quantity)
def send_message(image, telegram_message="No message"): if image: image_path = get_absolute_path(image) with open(image_path, 'rb') as img: telegram_send.send(images=[img], messages=[telegram_message]) else: telegram_send.send(images=None, messages=[telegram_message]) frappe.msgprint("The order has been sent to the Bakery")
def send_snapshots(snapshots, update, context): if len(snapshots) > 0: for photo_path in snapshots: with open(photo_path, 'rb') as photo: context.bot.send_photo(chat_id=update.effective_chat.id, photo=photo) with open(photo_path, 'rb') as photo: telegram_send.send(conf='conf/master.conf', images=[photo]) os.remove(photo_path)
async def unsubscribe(client, uuid): try: await client.stop_notify(uuid) except KeyError: # This happens on windows, I don't know why pass except Exception as e: telegram_send.send(messages=["`Exception: `" + str(e)], parse_mode="markdown") print("Exception: ", e)
def ready(self): if 'runserver' in sys.argv or sys.argv[0].endswith('gunicorn'): try: c = TSourceDocClient(TSourceDocClient.parse_args(['--timeout', '10'])) DeclarationsConfig.SOURCE_DOC_CLIENT = c except Exception as exp: try: telegram_send.send(messages=["request failed to source doc server from hostname={}".format(platform.node())]) except Exception as exp: pass
def enviar_mensaje_por_telegram(mensaje): """ Envía un mensaje a través del BotAvisador Argumentos: mensaje -- Mensaje a enviar """ telegram_send.send(messages=[mensaje])
def sendMessage(body, id): config = imgkit.config(wkhtmltoimage=('bin/wkhtmltoimage')) options = {'format': 'jpg'} img = imgkit.from_url( "http://www.manadafoodhouse.com.br/carrinho/detail/" + id, 'img-' + id + '.jpg', options=options, config=config) with open('img-' + id + '.jpg', "rb") as f: telegram_send.send(conf="telegramConf", messages=[body], images=[f])
def notify(self, dictionary): #if receiver == "stdout": print("Changed content:", dictionary) if self.receiver == 'mqtt': stationid = self.mqtt.get('stationid') broker = self.mqtt.get('broker') mqttport = self.mqtt.get('port') mqttdelay = self.mqtt.get('delay') client = self.mqtt.get('client') mqttuser = self.mqtt.get('user') mqttpassword = self.mqtt.get('password') topic = "{}/{}/{}".format(stationid, "statuslog", self.hostname) print("Done. Topic={},".format(topic)) print("Done. User={},".format(mqttuser)) client = mqtt.Client(client) if not mqttuser == None: client.username_pw_set(username=mqttuser, password=mqttpassword) print(broker, mqttport, mqttdelay) client.connect(broker, mqttport, mqttdelay) client.publish(topic, json.dumps(dictionary)) print('Update sent to MQTT') elif self.receiver == 'telegram': #try: # import Ok import telegram_send # except: # import error #try: # conf file exists # except: # send howto # requires a existing configuration file for telegram_send # to create one use: # python # import telegram_send # telegram_send.configure("/path/to/my/telegram.cfg",channel=True) tgmsg = '' for elem in dictionary: tgmsg += "{}: {}\n".format(elem, dictionary[elem]) telegram_send.send(messages=[tgmsg], conf=self.telegram.get('config'), parse_mode="markdown") print('Update sent to telegram') elif self.receiver == 'email': mailmsg = '' for elem in dictionary: mailmsg += "{}: {}\n".format(elem, dictionary[elem]) import acquisitionsupport as acs self.email = acs.GetConf(self.email.get('config')) #print(self.email) self.email['Text'] = mailmsg sendmail(self.email) print('Update sent to email') elif self.receiver == 'log': print('Updating logfile only') else: print("Given receiver is not yet supported")