def job(): print("[info] - Get messages") data = telegram.getMessage(token, True) print("[info] - Save messages") telegram.saveDataJson(token, data) message = [{ "key": "test", "text": "test passed", }, { "key": "button", "text": "choose a button", "inline": { "inline_keyboard": [[{ "text": "button1", "callback_data": "pressed1" }], [{ "text": "button2", "callback_data": "pressed2" }]] } }, { "key": "pressed1", "text": "button 1 work", }, { "key": "pressed2", "text": "button 2 work", }] print("[info] - Reply to messages") telegram.sendMessage(token, message)
def handleRanking(chatId, txt): table = ranking.getTable() n = len(ranking.getContestNames()) msg = "Current standings after __n={}__ contests:\n".format(n) msg_ineligible = ">> Contestants marked with \* are ineligible <<" tg.sendMessage( chatId, msg + "```\n" + table.toStr(width=25) + "```\n" + msg_ineligible)
def addReamainder(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.sendMessage(user['chat_id'], "Successfully set. Nearest at %s" % (datetime.datetime.now()+delta,))
def NSearchTelegram(user, keyword): facilities = getLocalDataFromKeyword(keyword) reply = '' cnt = 1 for data in facilities: reply += '[' + str(cnt) + '] ' reply += data['title'] + '\n' reply += data['description'] + '\n' reply += data['telephone'] + '\n' reply += data['address'] telegram.sendMessage(user, reply) reply = '' cnt += 1 reply = '지도를 표시하고 싶은 시설의 번호를 적어주십시오' telegram.sendMessage(user, reply)
def on_status(self, status): try: authorId = status.author.id in_reply_to_status_id = status.in_reply_to_status_id text = status.text if dao.checkExists(authorId) and in_reply_to_status_id is None \ and text.startswith("RT @") == False: twId = status.id screen_name = status.author.screen_name sourceLink = "https://twitter.com/%s/status/%s" % (screen_name, twId) text = status.text # timest = int(status.timestamp_ms) / 1000 # create_at_tm = datetime.fromtimestamp(timest, tz=pytz.timezone("Asia/Ho_Chi_Minh")).strftime( # '%Y-%m-%d %H:%M:%S') symbol = dao.getSymbol(authorId) if symbol is None: symbol = screen_name try: symbol = symbol.decode() except Exception as e: print(e) message = "<b>#%s</b>\n%s\n\n<a href='%s'>Source</a>" % ( symbol, text, sourceLink) # 468847123 # @aztoolChannelFollowTwitter textLower = text.lower() keywords = dao.getKeyword() for keyword in keywords: try: keyword = keyword[0].decode().lower() except Exception as e: keyword = keyword[0].lower() isValidKeyword = keyword in textLower if isValidKeyword: telegram.sendMessage(message, '@aztool_ignore_spam') break telegram.sendMessage(message, '@aztool_twitter') else: print("I dont care tw of %s " % status.author.screen_name) except Exception as e: print("Encountered Exception: %s " % e) pass
def handleCommand(command): command = command.lower() if command == "/ledon": led.ledOn() elif command == "/ledoff": led.ledOff() elif command == "/ledtoggle": led.ledToggle() elif command == "/options": options = "Options" #\\n/ledon\\n" #options += "ledon\n" #options += "/ledoff\n" #options += "/ledtoggle\n" telegram.sendMessage(idUser, options) else: print("Invalid Command")
def getUpdates(): messeges = telegram.getUpdates(params['offset']) for u in messeges: if 'message' in u: if u['update_id'] < params['offset']: print('Error') else: chat_id = u['message']['chat']['id'] text = u['message']['text'] params['offset'] = max(params['offset'], u['update_id']+1) try: parseAction(chat_id, text) except Exception: logging.error('Error! (%s, %s)' %(chat_id, text)) logging.error(traceback.print_exc()) telegram.sendMessage(chat_id, 'Parse error! Try again') db.meta.save(params)
def doMainTrain(user, string, overwrite=False): out_str = "" was_incorrect = False if(not overwrite): if string=='end': endTrain(user, string) return else: for w in user['words']: if w['word']==user['train']['word']: if user['train']['word']!=string.lower(): out_str+='Word is uncastable to origina\n' was_incorrect=True else: if user['train']['correct']==string: out_str+="Correct\n" if w['stage']<study_settings.max_stage: w['stage']+=1 w['expiration_date'] = datetime.datetime.utcnow() + study_settings.stages[w['stage']] else: out_str+="Incorrect\nThe correct one is %s \n" %(w['correct'],) if w['stage']>study_settings.min_stage: w['stage']-=1 was_incorrect=True trainlist = list(filter(lambda w: w['expiration_date'] < datetime.datetime.utcnow(), user['words'])) if len(trainlist)>1: if not was_incorrect: random.shuffle(trainlist) user['train']['word'] = trainlist[0]['word'] user['train']['correct'] = trainlist[0]['correct'] out_str += user['train']['word'] + "\n" else: out_str += "Not enough words\n" user['train']['type'] = 0 telegram.sendMessage(user['chat_id'], out_str)
def POST(self): s = settings() s.ReadSettings() if s.notiAPISecrets is not None: if not verifySign(s.notiAPISecrets, True): web.HTTPError('401 Unauthorized') return '' data = web.data() if isinstance(data, bytes): d = data.decode('UTF-8') elif isinstance(data, str): d = data else: web.HTTPError('500 Internal Server Error') return '' j = loads(d) mes = textc() APP_NAME = 'filterbox.field.APP_NAME' PACKAGE_NAME = 'filterbox.field.PACKAGE_NAME' TITLE = 'android.title' TEXT = 'android.text' WHEN = 'filterbox.field.WHEN' if APP_NAME in j: if PACKAGE_NAME in j: pn = j[PACKAGE_NAME] mes.addtotext(f"<b>{escape(j[APP_NAME])} ({escape(pn)})</b>") else: mes.addtotext(f"<b>{escape(j[APP_NAME])}</b>") if TITLE in j: mes.addtotext(f"<b>{escape(j[TITLE])}</b>") if TEXT in j: mes.addtotext(escape(j[TEXT])) mes.addtotext(strftime(ISO8601_FORMAT, gmtime(j[WHEN] / 1000))) while len(mes): sendMessage(s.notiAPITelegraBotChatId, mes.tostr(), s.notiAPITelegramBotAPIKey, 'HTML', True) return ''
def POST(self): se = settings() se.ReadSettings() lan = getlang() web.header('Content-Language', lan) web.header('Content-Type', 'application/json; charset=UTF-8') i18n = getdict('sendMsgToMe', lan) inp = web.input() content = inp.get("content") if content is None or len(content) == 0: inf = {'code': -3, 'msg': i18n['NEEDCON']} return dumps(inf, ensure_ascii=False, separators=sep) name = inp.get("name") if name is None or len(name) == 0: inf = {'code': -4, 'msg': i18n['NEEDN']} return dumps(inf, ensure_ascii=False, separators=sep) checked, info = checkCaptcha2() inf = {} inf['code'] = 0 if checked else -1 if se.debug: inf['debugInfo'] = info if not checked: inf['msg'] = info['msg'] if checked: if se.telegramchatid is None: inf['code'] = -2 inf['debugInfo2'] = {'code': -1, 'msg': 'No Chat Id.'} else: try: ip = web.ctx['ip'] if ip is None: ip = '' except: ip = '' ilan = web.input().get("lan") if ilan is None: ilan = 'Unknown' addt = f' ({ilan})' if ip == '' else f' ({ip}, {ilan})' text = f"{name}{addt}: {content}" sended, info = sendMessage(se.telegramchatid, text) inf['code'] = 0 if sended else -4 if not sended: inf['msg'] = info['msg'] if se.debug: inf['debugInfo2'] = info return dumps(inf, ensure_ascii=False, separators=sep)
def endTrain(user, string): user['train']['type'] = 0 telegram.sendMessage(user['chat_id'], "Train ended", reply_markup=telegram.hideKeyboard)
def sendmessage(): message = request.args.get("message") telegram.sendMessage(message) return render_template('send.html', message=message)
def marketBuy(orderAmt, div): # Get Balances usdbal, btcbal = getBal() # Calculate order amounts usdorderAmt = round_down( (float(usdbal) / div - 0.0036 * (float(usdbal) / div)), 2) ask = round_down(float(r.get_ticker("BTCUSD")['ask']) - 0.05, 2) btcorderAmt = round_down((usdorderAmt / float(ask)), 8) origOrderAmt = btcorderAmt # Place a limit order at a little below ask price ordrplcd = 0 while (True): msg = "Placing new limit buy order @" + str(ask) tel.sendMessage(chatid, msg) order = r.new_order("BTCUSD", str(btcorderAmt), str(ask), "buy", ["maker-or-cancel"]) try: time.sleep(5) orderid = order['order_id'] ordrplcd = 1 except: ask = round_down(float(r.get_ticker("BTCUSD")['ask']) - 0.05, 2) ordrplcd = 0 if ordrplcd == 1: break msg = "Initial buy limit order placed @" + str(ask) tel.sendMessage(chatid, msg) # if order['is_cancelled'] == True and order['reason'] == 'MakerOrCancelWouldTake': # return # Check whether limit order has been filled # Follow market price to place new limit orders # After time limit of 6 min, place market order start = time.time() market = 0 neword = 0 while (True): if abs(start - time.time()) > 360: market = 1 break status = r.status_of_order(orderid) if status['is_live'] is False and status[ 'is_cancelled'] == False and status[ 'original_amount'] == status['executed_amount']: break if status['is_cancelled'] == True and status[ 'original_amount'] != status['executed_amount']: neword = 1 if (abs(float(r.get_ticker("BTCUSD")['last']) - float(order['price'])) > 15) or (neword == 1): if neword == 0: # Cancel latest limit order r.cancel_order(orderid) # Create new one # Check if trade partially filled partfill = 0 for trade in r.get_past_trades("BTCUSD"): if trade['order_id'] == str(orderid): partfill = round_down(float(trade['amount']), 8) # Calculate order amounts btcorderAmt = btcorderAmt - partfill ask = round_down(float(r.get_ticker("BTCUSD")['ask']) - 0.05, 2) # Place a limit order at a little below ask price ordrplcd = 0 while (True): msg = "Placing new limit buy order @" + str(ask) tel.sendMessage(chatid, msg) order = r.new_order("BTCUSD", str(btcorderAmt), str(ask), "buy", ["maker-or-cancel"]) try: time.sleep(5) orderid = order['order_id'] ordrplcd = 1 except: ask = round_down( float(r.get_ticker("BTCUSD")['ask']) - 0.05, 2) ordrplcd = 0 if ordrplcd == 1: break msg = "New limit order placed @" + str(ask) tel.sendMessage(chatid, msg) if market == 1: # Check if trade partially filled partfill = 0 for trade in r.get_past_trades("BTCUSD"): if trade['order_id'] == str(orderid): partfill = round_down(float(trade['amount']), 8) # Calculate order amounts btcorderAmt = btcorderAmt - partfill msg = "Market order for " + str( btcorderAmt) + "BTC | Filled amount on limit price " + str( partfill) + "BTC" tel.sendMessage(chatid, msg) markExec = 0 while (True): currprice = round_down(float(r.get_ticker("BTCUSD")['ask']), 2) msg = "Placing new market buy order @" + str(currprice) tel.sendMessage(chatid, msg) order = r.new_order("BTCUSD", str(btcorderAmt), str(currprice), "buy", ["immediate-or-cancel"]) try: time.sleep(5) orderid = order['order_id'] status = r.status_of_order(orderid) if status['is_live'] is False and status[ 'is_cancelled'] == False and status[ 'original_amount'] == status['executed_amount']: markExec = 1 if status['is_cancelled'] == True and status[ 'original_amount'] != status['executed_amount']: orig = float(status['original_amount']) * float( status['price']) exec = float(status['executed_amount']) * float( status['price']) if abs(orig - exec) <= 5: msg = "Most of market order filled, Fell short by $" + str( abs(orig - exec)) tel.sendMessage(chatid, msg) markExec = 1 execAmt = round_down(float(status['executed_amount']), 8) btcorderAmt = btcorderAmt - execAmt except Exception as e: markExec = 0 msg = e + " Market order failed. Retrying" tel.sendMessage(chatid, msg) if markExec == 1: break buyPrice = round(float(r.get_past_trades("BTCUSD")[0]['price']), 2) buyFee = round(float(r.get_past_trades("BTCUSD")[0]['fee_amount']), 2) return buyPrice, buyFee buyPrice = round(float(r.get_past_trades("BTCUSD")[0]['price']), 2) buyFee = round(float(r.get_past_trades("BTCUSD")[0]['fee_amount']), 2) return buyPrice, buyFee
def removeRemainder(user, text): remainder.remove_job(user) telegram.sendMessage(user['chat_id'], "Removed")
def getWalls(**kwargs): r = requests.get(domain + urlencode(kwargs)) return r.json() if __name__ == '__main__': request = getWalls(domain='kino_mania', count=5, offset=1, access_token=ACCESS_TOKEN, v='5.95') walls = request['response']['items'] maxId = db_wall.getLastIdWall() for wall in walls: if maxId: if int(maxId) < int(wall['id']): if 'attachments' in wall: if "photo" in wall['attachments'][0]: photos = wall['attachments'][0]['photo']['sizes'] photo_for_send = photos[len(photos) - 1] telegram.sendPhoto(wall['text'], photo_for_send['url']) else: telegram.sendMessage(wall['text']) db_wall.insertIdWall(str(walls[0]['id']))
def help(user, text): telegram.sendMessage(user['chat_id'], help_text)
def start(user, text): telegram.sendMessage(user['chat_id'], """ Welcome I am an EnglishWordRepeater bot. To learn how to use me, print /help """)
def getListWord(user, text): str_out = "\n".join(["%s" % (w['correct'], ) for w in user['words']]) telegram.sendMessage(user['chat_id'], str_out)
RECEIVER_MAIN = os.environ.get("RECEIVER_MAIN") RECEIVER_LOGS = os.environ.get("RECEIVER_LOGS") RECEIVER_ALERT = os.environ.get("RECEIVER_ALERT") try: # scrape full HTML from Manavakcina homepage response = requests.get("https://manavakcina.lv/") if os.path.isfile("previous.html"): # Check and notify if HTML code length in website is different from previous scrape previousLength = len( open("previous.html", mode="r", encoding="utf-8").read()) currentLength = len(response.text) if previousLength == currentLength: messageContent = "Scrape successful, no changes detected. {}".format( datetime.now().time()) sendMessage(RECEIVER_LOGS, messageContent) else: messageContent = "Koda izmaiņas Manavakcīna mājaslapā!" sendMessage(RECEIVER_MAIN, messageContent) else: sendMessage(RECEIVER_LOGS, "First Scrape in this Session") # update previous.html with latest scraper data file = open("previous.html", mode="w", encoding="utf-8") file.write(response.text) file.close() except Exception as e: sendMessage(RECEIVER_ALERT, str(e))
def invalidCommand(cid, msg): tg.sendMessage(cid, "Invalid command!")
def func(): telegram.sendMessage(user['chat_id'], "Hey! It is time to learn")
def msgAll(text): for chatId in chatIds: tg.sendMessage(chatId, text)
def eraseLastWord(user, text): if(len(user['words'])>0): str_out = "%s - %s" % (user['words'][-1]['en'], user['words'][-1]['ru']) user['words'] = user['words'][:-1] telegram.sendMessage(user['chat_id'], "Last word erased\n" + str_out)
# Stop prices stopPrice = {1: 0, 2: 0, 3: 0} # Target prices tgtPrice = {1: 0, 2: 0, 3: 0} # Exit prices exitPrice = {1: 0, 2: 0, 3: 0} # Tracks number of targets hit; Helps to trail stop losses and set new targets tgtHit = {1: 0, 2: 0, 3: 0} # Tracks crossover occurrences and prevents overtrading lockState = {1: 0, 2: 0, 3: 0} unlockState = {1: 300, 2: 300, 3: 300} # Heartbeat hrtbt = 0 msg = "MAEVE started @" + str(datetime.now()) tel.sendMessage(chatid, msg) while (True): logging.info("############################################") logging.info("Strategy Run @" + str(datetime.now())) logging.info("#############################################") # Monitor heartbeat hrtbt += 1 if hrtbt == 120: msg = "MAEVE hard at work @" + str(datetime.now()) tel.sendMessage(chatid, msg) hrtbt = 0 # Get current price