def create(self): if self.is_exist(): logging.info("Chat already exist") return False insert_chat(self.chat_id) botan.track(str(config.get("ya_token")), self.chat_id, {}, 'CreateUser') return True
def feedback(message): sendmail(message.text, message.from_user.username) uid = message.from_user.id message_dict = json.dumps(message, default=lambda o: o.__dict__) botan.track(metrika_token, uid, message_dict, 'feedback') msg = bot.send_message(message.chat.id, "Thank you for your feedback!")
def send_to_botan(self, data): name = data['name'] message = {} if 'title' in data: uid = data['chat_id'] else: uid = data['user_id'] print 'Sending data to botan', data botan.track(self.botan_token, uid, message, name)
def run(self, id, args, message_date): message = "" if (len(args) > 0): word = args[0] post_texts = search_posts(word) for post_text in post_texts: message += post_text[0] + "\n\n" message = "Постов не найдено" if message == "" else message self.bot.broadcast_message(id, message) botan.track(str(config.get("ya_token")), id, {}, 'SearchCommand')
def send_log(message, cmd=None): if cmd is not None: try: botan.track(botan_token, message.from_user.id, to_json(message), cmd) except Exception: pass timestamp = strftime("%Y-%m-%d %H:%M:%S") group_info = "" text = "" if is_group(message): group_info = "in group %s (%s)" % (message.chat.title, message.chat.id) if message.text is not None: text = "[%s]\n@%s\n(%s %s - %s)\n\n%s\n\n%s" %\ (timestamp, message.from_user.username, message.from_user.first_name, message.from_user.last_name, message.from_user.id, message.text, group_info) elif message.caption is not None: text = "[%s]\n@%s\n(%s %s - %s)\n\n%s\n\n%s" %\ (timestamp, message.from_user.username, message.from_user.first_name, message.from_user.last_name, message.from_user.id, message.caption, group_info) elif message.left_chat_member is not None: text = "[%s]\n@%s\n(%s %s - %s)\n\n%s %s (%s)" %\ (timestamp, message.left_chat_member.username, message.left_chat_member.first_name, message.left_chat_member.last_name, message.left_chat_member.id, "removed from group", message.chat.title, message.chat.id) elif message.new_chat_member is not None: text = "[%s]\n@%s\n(%s %s - %s)\n\n%s %s (%s)" %\ (timestamp, message.new_chat_member.username, message.new_chat_member.first_name, message.new_chat_member.last_name, message.new_chat_member.id, "added in group", message.chat.title, message.chat.id) log_bot.send_message(admin_id, text)
def send_welcome(message): msg = bot.send_message(message.chat.id, """\ Hi there, I am Freelance bot! Let's start. Write keywords separated commas for your job search. For example: python, api, crawler """) uid = message.from_user.id message_dict = json.dumps(message, default=lambda o: o.__dict__) botan.track(metrika_token, uid, message_dict, 'Start') bot.register_next_step_handler(msg, set_query)
def run(self, id, args, message_date): if self.check_status(id, args) == False: c = Chat(id) botan.track(str(config.get("ya_token")), id, {}, 'SubscribeStopCommand') channels = config.get("channels"); channel = args[0] if (len(channels) > 1) else channels[0]["name"] try: c.unsubscribe_all(channel) message = str(config.get("stop_message")) self.bot.broadcast_message(id, message) except NameError: self.bot.broadcast_message(id, str(config.get("doesntexist_message")))
def track(uid, message, name='Message'): if tkn is not None: arg = message try: arg = { 'text': message.text, 'date': message.date.isoformat() #'from_user': message.from_user.__dict__ } except: pass botan.track(tkn, uid, arg, name)
def documents_handler(message): file_info = bot.get_file(message.document.file_id) downloaded_file = bot.download_file(file_info.file_path) result = validate_file_content(downloaded_file) if result['status']: bot.reply_to(message=message, text=f'https://hastebin.com/{result["result"]}', parse_mode='HTML') botan.track(os.environ.get('botan_key'), message.chat.id, message, 'New paste created.') else: bot.reply_to(message, text=f'`Error: {result["message"]}`', parse_mode='Markdown')
def run(self, id, args, message_date): if self.check_status(id, args) == False: c = Chat(id) botan.track(str(config.get("ya_token")), id, {}, 'SubscribeStopCommand') channels = config.get("channels") channel = args[0] if (len(channels) > 1) else channels[0]["name"] try: c.unsubscribe_all(channel) message = str(config.get("stop_message")) self.bot.broadcast_message(id, message) except NameError: self.bot.broadcast_message( id, str(config.get("doesntexist_message")))
def get(bot, update, user_data): """Send a dev message when the command /get is issued.""" botan.track(botan_token, update.message.from_user, update.message.to_dict(), "get") update.message.from_user user_data['count'] = 0 messages = ubot.get_sources_sites() button_list = [InlineKeyboardButton(s, callback_data=s) for s in messages] reply_markup = InlineKeyboardMarkup(build_menu(button_list, n_cols=3), one_time_keyboard=True) bot.send_message(update.message.chat_id, text="Выберите сайт", reply_markup=reply_markup) return SITE
def add(msg): find = db.users.find_one({"id": str(msg.chat.id)}) i18n.set("locale", find["lang"]) m = msg.text.replace("/add", "") markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True) markup.add(i18n.t("msg.cancel")) if m == "": bot.send_message(msg.chat.id, i18n.t("msg.enter"), reply_markup=markup) bot.register_next_step_handler(msg, add_hand) else: save_task(msg, msg.chat.id, m) botan.track(botan_key, msg.chat.id, msg, 'Add task') return
def subway(bot, update): number_of_day = date.weekday(date.today() + timedelta(days=( datetime.today() + timedelta(hours=3)).day > datetime.today().day)) subs = [ sub[:-1:] for sub in open('WeekOfSubsEn.txt', 'r', encoding='utf-8') ][number_of_day] bot.send_message(chat_id=update.message.chat_id, text='And the sub of the day for today is:\n' + subs, parse_mode='Markdown', disable_web_page_preview=True) bot.send_photo(chat_id=update.message.chat_id, photo=open(fr'Images/{number_of_day}.png', 'rb')) botan.track(YANDEX_TOKEN, update.message.chat.id, update.message, 'sub')
def callback_inline(call): find = db.users.find_one({"id": str(call.message.chat.id)}) i18n.set("locale", find["lang"]) db.users.update({"id": str(call.message.chat.id)}, {"$pull": {"tasks": find["tasks"][int(call.data)]}}, upsert=False) bot.answer_callback_query(call.id, text=i18n.t("msg.completed")) find = db.users.find_one({"id": str(call.message.chat.id)}) if len(find["tasks"]) != 0: bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text=i18n.t("msg.taskhelp"), reply_markup=tasks_kb(find["tasks"])) botan.track(botan_key, call.message.chat.id, call.message, 'Delete task') return else: bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text=i18n.t("msg.notask"))
def start(bot, update): greeting = '@' + update.message.chat.username if update.message.chat.type in { 'private' } else 'pussies' bot.send_message( chat_id=update.message.chat_id, text="Hi, {}!\nI'm here to help you to know " "the sub of the day, cause I can print it (/sub)".format(greeting)) bot.send_message(chat_id=update.message.chat_id, text="If it's uncomfortable for you to read in English, " "you can switch the language to Russian") language(bot, update) botan.track(YANDEX_TOKEN, update.message.chat.id, update.message, 'start')
def sneeze(message): user_key = get_key(message.chat.id) if (get_key(message.chat.id) not in location.keys()): location[user_key] = pickle_load(user_key)[-5:] location[user_key].append( [location[user_key][-1][0] + 1, 'None', 'None', message.date]) # add sneeze count bot.send_message( message.chat.id, "Bless you! It's your {} sneezes".format( str(location[user_key][-1][0]))) pickle_dump(user_key, location[get_key(message.chat.id)][-1]) location[user_key] = pickle_load(user_key)[-5:] if location[user_key][-1][0] % 10 == 0: bot.send_sticker(message.chat.id, config.PLANTAIN_STICK) #send podorojnik sticker botan.track(config.BOTAN_KEY, message.chat.id, message, '/sneeze')
def send_welcome(message): w = requests.get( "https://api.crex24.com/CryptoExchangeService/BotPublic/ReturnTicker?request=[NamePairs=BTC_SLD]" ) sld = w.json() sld_btc = Decimal(sld['Tickers'][0]['Last']) #Получили цену в БТЦ bot.send_message(message.chat.id, u'\U0001F4B0 SLD is worth: *' + '{0:.8f}'.format(sld_btc) + ' Btc*', parse_mode='Markdown') botan.track(botan.botan_token, message.chat.id, message, 'BTC')
def test(bot, update, args): botan.track(BOTAN_TOKEN, update.message.chat_id, update.message.to_dict(), 'test') url = args[0].lower() try: r = requests.head(url) if r.status_code == 200: bot.sendMessage(chat_id=update.message.chat_id, text="Url %s is alive (status code 200)" % url) else: bot.sendMessage(chat_id=update.message.chat_id, text="Status code of url %s is %s" % (url, r.status_code)) except: bot.sendMessage(chat_id=update.message.chat_id, text="Error for url %s" % url)
def event_processor(): while True: if len(events_to_process) <= 0: continue #recupera il primo elemento da processare event_processor_lock.acquire() ev = events_to_process.pop(0) event_processor_lock.release() botan.track(ev["uid"], ev["message"], ev["name"]) print("Processed stats event: " + ev["name"]) time.sleep(1)
def run(self, id, args, message_date): channels = config.get("channels"); if len(channels) == 1: self.send_last_posts(id, channels[0]["name"]) botan.track(str(config.get("ya_token")), id, {}, 'LastCommand') return; if (len(args) > 0): post_type = str(args[0]) for c in channels: if c['name'] == post_type and c['forced'] == False: self.send_last_posts(id, post_type) return; self.bot.broadcast_message(id, str(config.get("doesntexist_message"))) else: self.bot.broadcast_message(id, str(config.get("last_message"))) botan.track(str(config.get("ya_token")), id, {}, 'LastCommand')
def run(self, id, args, message_date): channels = config.get("channels") if len(channels) == 1: self.send_last_posts(id, channels[0]["name"]) botan.track(str(config.get("ya_token")), id, {}, 'LastCommand') return if (len(args) > 0): post_type = str(args[0]) for c in channels: if c['name'] == post_type and c['forced'] == False: self.send_last_posts(id, post_type) return self.bot.broadcast_message(id, str(config.get("doesntexist_message"))) else: self.bot.broadcast_message(id, str(config.get("last_message"))) botan.track(str(config.get("ya_token")), id, {}, 'LastCommand')
def command_stats(message): UID = message.chat.id UTXT = message.text db = SQLighter() result = db.select_all() chn = db.select_all_chn() db.close() users = [] for i in result: if i[1] not in users: users.append(i[1]) msg = bot.send_message(UID, '🚀 *Статистика*\nАктивных страниц: *%s*\nАктивных пользователей: *%s*\n' \ 'Активных каналов: *%s*\n\nВерсия бота: *2.2.1*' % (len(result), len(users), len(chn)), \ parse_mode='Markdown') botan.track(BOTAN_TOKEN, message.chat.id, message, 'Просмотр статистики')
def send_welcome(message): global sub sub = [line.rstrip('\n') for line in open(subfile, 'rt')] if str(message.chat.id) not in sub: bot.send_message( message.chat.id, "Добро пожаловать в мир постыдных историй! Расскажи свою историю анонимно! \n Добавляйте фото, ставьте оценки!\n список команд: \n /photo - Случайное фото \n /story - Случайная история \n \n /subscribe - подписка на истории и фото!!! \n /help - помощь \nДля отключения рекламы - добавьте фото или историю!!! \n Для связи с админом просто напишите сообщение в чат.", reply_markup=markup_start_ne) else: bot.send_message( message.chat.id, "Добро пожаловать в мир постыдных историй! Расскажи свою историю анонимно! \n Добавляйте фото, ставьте оценки!\n список команд: \n /photo - Случайное фото \n /story - Случайная история \n \n /subscribe - подписка на истории и фото!!! \n /help - помощь \nДля отключения рекламы - добавьте фото или историю!!! \n Для связи с админом просто напишите сообщение в чат.", reply_markup=markup_start) botan.track(botan_key, message.chat.id, message, 'Добро пожаловать!')
def handler_command_help(message): bot.send_message( message.chat.id, "Привет! Я TwiggBot. " "Я создан, что бы помогать владельцам инетернет-магазинов управлять и следить за " "их интернет-магазином. Я пока на стадии разработки, но кое-что уже умею." "\n /help - Помощь." "\n /ya - Доступ к сервисам яндекса. ( Нужно для /stats и /info.)" "\n /stats - Получение статистики." "\n /track <трек номер> - отслеживание посылок." "\n /postoffice <e-mail> - получеие статистики рассылки." "\n /setpush - Проверка сайта." "\n /info <сайт> - СКОРО!" "\n /delivery CКОРО!" "\n /managerDirect - СКОРО!" "\nЕсли есть какие - то пожелания, вопросы или жалобы обращайтесь к моему создателю @marat_sher!" ) botan.track(const.botan_token, message.chat.id, message, "Команда /help")
def botanio(bot, update, message, event_name, uid): try: message_dict = update.message.to_dict() except: message_dict = "{}" try: print(botan.track(botan_token, uid, message_dict, event_name)) except Exception as e: print(e)
def start(message): if exist("pickles/{}.pickle".format(get_key( message.chat.id))): # use piclkes file instead database bot.send_message(message.chat.id, "You have already started") else: location[get_key(message.chat.id)] = [[0]] # initialize new user bot.send_message(message.chat.id, "Hi. I'm a bot that collect sneezes statistics") helpme(message) # send command description keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True) # button class button_geo = types.KeyboardButton(text="SNEEZED!! !", request_location=True) # button keyboard.add(button_geo) # create button bot.send_message(message.chat.id, "Tap when sneezed", reply_markup=keyboard) # add button botan.track(config.BOTAN_KEY, message.chat.id, message, '/start')
def locat(message): user_key = get_key( message.chat.id) # get_key return hash string from user id if user_key not in location.keys(): # load last 5 location location[user_key] = pickle_load(user_key)[ -5:] # it is need if program will failed location[user_key].append([location[user_key][-1][0] + 1, message.location.longitude, \ message.location.latitude, message.date]) # add sneeze count bot.send_message( message.chat.id, "Bless you! It's your {} sneezes".format( str(location[user_key][-1][0]))) pickle_dump(user_key, location[get_key( message.chat.id)][-1]) # after recording rewrite to pickles location[user_key] = pickle_load(user_key)[-5:] if location[user_key][-1][0] % 10 == 0: bot.send_sticker(message.chat.id, config.PLANTAIN_STICK) #send podorojnik sticker botan.track(config.BOTAN_KEY, message.chat.id, message, '/location')
def send_welcome(message): """ Функция, показывающая reply_markup с кнопками меню :param message: Сообщение, присланное пользователем """ botan.track(botan_key, message.chat.id, message.text, strings["menu"]["menu_name"]) global faq_flag if message.chat.id in faq_flag: del faq_flag[message.chat.id] markup = types.ReplyKeyboardMarkup() for button in strings["menu"]["keyboard_buttons"]: markup.add(button) bot.send_message(message.chat.id, strings["menu"]["message"], reply_markup=markup)
def send_welcome(message): params = {'limit': 1} r = requests.get('https://btc-alpha.com/api/charts/SLD_BTC/D/chart', params=params) d = r.json() low = Decimal(d[0]['low']) high = Decimal(d[0]['high']) vol = Decimal(d[0]['volume']) params = { 'limit_sell': 1, 'limit_buy': 1, 'group': 1, } alfa = requests.get("https://btc-alpha.com/api/v1/orderbook/SLD_BTC/", params=params) alfa_res = alfa.json() asell = Decimal(alfa_res['sell'][0]['price']) a_sell_coin = Decimal(alfa_res['sell'][0]['amount']) abuy = Decimal(alfa_res['buy'][0]['price']) a_buy_coin = Decimal(alfa_res['buy'][0]['amount']) bot.reply_to( message, 'Btc-Alpha.com:' + '\nPair Name: Btc-Soldo' + '\nLow Price: ' + '{0:.8f}'.format(low) + ' Btc' + '\nHigh Price: ' + '{0:.8f}'.format(high) + " Btc" + '\nVolume: ' + '{0:.8f}'.format(vol) + " Sld" + '\nBuy: ' + '{0:.8f}'.format(abuy) + ' Btc' + '\nBuy Count: ' + '{0:.2f}'.format(a_buy_coin) + ' Sld' + '\nSell: ' + '{0:.8f}'.format(asell) + ' Btc' + '\nSell Count: ' + '{0:.2f}'.format(a_sell_coin) + ' Sld') botan.track(botan.botan_token, message.chat.id, message, 'alpha')
def settings_choose(message): UID = message.chat.id UTXT = message.text db = SQLighter() if len(db.select_all_by_uid(UID)) > 0: key_nums = types.ReplyKeyboardMarkup(row_width=5, resize_keyboard=True) result = db.select_all_by_uid(UID) counter = ['NULL'] pages_list = '' for item in result: counter.append({'id': item[0]}) if item[5] == 0: pages_list += '*#%s* ∙ Из *%s* в *чат с ботом*\n' % (str(len(counter) - 1), \ item[3].encode('utf-8')) key_nums.add( types.KeyboardButton('#%s' % (str(len(counter) - 1)))) else: pages_list += '*#%s* ∙ Из *%s* в *канал %s*\n' % (str(len(counter) - 1), \ item[3].encode('utf-8'), item[6].encode('utf-8')) key_nums.add( types.KeyboardButton('#%s' % (str(len(counter) - 1)))) key_nums.row(types.KeyboardButton('⬅️ Вернуться в меню')) with io.open(str(UID) + '.UID', 'w', encoding='utf-8') as file: # Создаём временный .UID файл для хранения связок ID из базы — номер в клавиатуре file.write( unicode(json.dumps({'data': counter}, ensure_ascii=False))) msg = bot.send_message(UID, pages_list, parse_mode='Markdown', reply_markup=key_nums) bot.send_message( UID, 'Нажми на номер страницы, которую хочешь изменить или удалить.') botan.track(BOTAN_TOKEN, message.chat.id, message, 'Настройки пользовательских страниц') bot.register_next_step_handler(msg, settings_page) else: msg = bot.send_message(UID, 'Похоже, *ты не добавил ещё ни одной страницы*.\nНажми /add, чтобы' \ ' добавить.', parse_mode='Markdown', reply_markup=key_default) db.close()
def tutorial(self, user, command): # extract text and address if command in self.commands: text = TDO.Update.get_text(self.update, command) words = text.split() if len(words) and words[0].startswith("@") and len(words[0]) > 1: address = words[0][1:] else: address = '' if not user['state']: self.change_user_state(user['user_id'], 'state', 'training0') return tutorial0.format(user['first_name'], emoji_smile) elif user['state'] == 'training0': if command in ['todo', 'todo@todobbot', 't']: self.change_user_state(user['user_id'], 'state', 'training1') print 'Sent todo to botan:', botan.track(self.botan_token, self.update['chat']['id'], self.update, '/todo') result = self.todo(text, address) return result + tutorial1.format(emoji_wink) else: return tutorial_er0 elif user['state'] == 'training1': if command in ['list', 'list@todobbot', 'l']: self.change_user_state(user['user_id'], 'state', 'training2') print 'Sent list to botan:', botan.track(self.botan_token, self.update['chat']['id'], self.update, '/list') result = self.list(address) return result + tutorial2.format(emoji_thumb) else: return tutorial_er1 elif user['state'] == 'training2': if command in ['done', 'done@todobbot', 'd']: self.change_user_state(user['user_id'], 'state', 'training3') print 'Sent done to botan:', botan.track(self.botan_token, self.update['chat']['id'], self.update, '/done') result = self.done(text, address) return result + tutorial3.format(emoji_clap) else: return tutorial_er2 elif user['state'] == 'training3': if command in ['completed', 'completed@todobbot', 'c']: self.change_user_state(user['user_id'], 'state', 'training4') self.change_user_state(user['user_id'], 'trained', True) result = self.completed(text) return result + tutorial4.format(emoji_one, emoji_two, emoji_sparkles) else: return tutorial_er3
def save_task(msg, cid, text): find = db.users.find_one({"id": str(cid)}) i18n.set("locale", find["lang"]) if find["notify"]: markup = gen_markup(i18n.t("msg.add"), i18n.t("msg.tasks"), i18n.t("msg.help"), i18n.t("msg.rate"), i18n.t("msg.offn"), i18n.t("msg.setl")) else: markup = gen_markup(i18n.t("msg.add"), i18n.t("msg.tasks"), i18n.t("msg.help"), i18n.t("msg.rate"), i18n.t("msg.onn"), i18n.t("msg.setl")) if len(text) < 50: if text not in find["tasks"]: db.users.update({"id": str(cid)}, {"$push": {"tasks": text}}, upsert=False) bot.send_message(cid, i18n.t("msg.added"), reply_markup=markup) botan.track(botan_key, cid, msg, 'Add task') return else: bot.send_message(cid, i18n.t("msg.inlist"), reply_markup=markup) else: bot.send_message(cid, i18n.t("msg.long"), reply_markup=markup)
def handle_start_help(message): start = """ https://github.com/dposokhov/crazy_cube_solve /solve: На вход бот получает строку из 54 символов. UUUUUUUUURRRRRRRRRFFFFFFFFFDDDDDDDDDLLLLLLLLLBBBBBBBBB /color-solve На вход бот получает строку из 54 символов. WWWWWWWWWOOOOOOOOOBBBBBBBBBYYYYYYYYYRRRRRRRRRGGGGGGGGG Кубик нужно расположить Нужно построчно ввести все цвета с граней в такой последовательности: Up, Right, Front, Down, Left, Back THE=====END """ bot.reply_to(message, start, reply_markup=markup) botan.track(config.botan_key, message.chat.id, message, 'start')
def start(msg): find = db.users.find_one({"id": str(msg.chat.id)}) if find: i18n.set("locale", find["lang"]) if find["notify"]: markup = gen_markup(i18n.t("msg.add"), i18n.t("msg.tasks"), i18n.t("msg.help"), i18n.t("msg.rate"), i18n.t("msg.offn"), i18n.t("msg.setl")) else: markup = gen_markup(i18n.t("msg.add"), i18n.t("msg.tasks"), i18n.t("msg.help"), i18n.t("msg.rate"), i18n.t("msg.onn"), i18n.t("msg.setl")) bot.send_message(msg.chat.id, i18n.t("msg.hi_back"), reply_markup=markup) botan.track(botan_key, msg.chat.id, msg, 'Returned user') return else: markup = gen_markup(i18n.t("msg.add"), i18n.t("msg.tasks"), i18n.t("msg.help"), i18n.t("msg.rate"), i18n.t("msg.offn"), i18n.t("msg.setl")) db.users.save({"id": str(msg.chat.id), "tasks": [], "notify": True, "lang": "en"}) bot.send_message(msg.chat.id, i18n.t("msg.hi"),reply_markup=markup) botan.track(botan_key, msg.chat.id, msg, 'New user') return
def fObl(message): message.text = str(message.text).translate(non_bmp_map)[-1] == '�' and str( message.text).translate(non_bmp_map)[:-1] or str( message.text).translate(non_bmp_map) if message.text not in fObl.comands: raise NotComands if message.text not in fObl.obl: for i in dataPrice[language[str(message.from_user.id)]]: if message.text in dataPrice[language[str( message.from_user.id)]][i]: fObl.obl = i break fCity.comands = [message.text] fCity.d = message.text fCity.l = 0 fCity(message) else: keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True) a = list(dataPrice[language[str(message.from_user.id)]][message.text]) if not len(a): bot.send_message(message.chat.id, config.text['verySorry'][language[str( message.from_user.id)]], reply_markup=types.ReplyKeyboardRemove()) start(message) return 0 fCity.comands = a[:] # keyboard.add(*[types.KeyboardButton(str(name)) for name in a]) keyboard.add( types.KeyboardButton(config.text['home'][language[str( message.from_user.id)]])) city = bot.send_message(message.chat.id, config.text['textCity'][language[str( message.from_user.id)]], reply_markup=keyboard) fCity.d = a fObl.obl = message.text fCity.l = 1 bot.register_next_step_handler(city, fCity) botan.track(config.botan_key, message.chat.id, message, message.text)
def send_welcome(message): bot.send_message( message.chat.id, u'\U0000270ACurrently open votes to support Soldo :' + '\n [Vote to add SLD on altcoinexchange.com](https://feedback.altcoinexchange.com/suggestions/3104/soldo-sld) (pending...' u'\U0001F55C)' + '\n [Vote to add SLD on nextexchange](https://nextexchange.featureupvote.com/suggestions/3163/soldo-sld) (pending...' u'\U0001F55C)' + '\n [Vote to add SLD on lescovex.com](https://lescovex.featureupvote.com/suggestions/5524/soldo-sld) (pending...' u'\U0001F55C)' + '\n [Vote to add SLD on c-cex.com](https://c-cex.com/?id=vote&coin=sld) (pending...' u'\U0001F55C)' + '\n [Vote to add SLD on quantadex.zendesk.com](https://quantadex.zendesk.com/hc/en-us/community/posts/360002787811-Soldo-SLD-) (pending...' u'\U0001F55C)', parse_mode='Markdown', disable_web_page_preview=True) botan.track(botan.botan_token, message.chat.id, message, 'vote')
def action(message): if message.text not in action.comands: raise NotComands imgs = re.findall( r'<g>[\s]*?(http.*?jpg.*?|http.*?png.*?|http.*?gif.*?)</g>', action.rez[message.text][0], re.DOTALL) texts = re.split(r'[\s]*?<g>.*?</g>[\s]*?', action.rez[message.text][0], re.DOTALL) keyboard = types.InlineKeyboardMarkup() keyboard.add(*[ types.InlineKeyboardButton( text=config.text['textMoreInfo'][language[str( message.from_user.id)]], url=action.rez[message.text][1][:18] + str(language[str(message.from_user.id)] == 'ua' and '/uk' or '') + action.rez[message.text][1][18:]) ]) bot.send_message(message.chat.id, '<b>{0}</b>'.format(message.text), parse_mode='HTML') for i in range(len(imgs)): if len(texts[i]) != 0: bot.send_message(message.chat.id, str(texts[i]), parse_mode='HTML') murl = re.search(r'(http.*?jpg|http.*?png|http.*?gif)', imgs[i]).group(0) desc = imgs[i].replace(murl, '') if texts[-1] == "" and i + 1 == len(imgs): mess = bot.send_photo(message.chat.id, murl, desc, reply_markup=keyboard) break else: bot.send_photo(message.chat.id, murl, desc) else: mes = bot.send_message(message.chat.id, texts[-1], reply_markup=keyboard) botan.track(config.botan_key, message.chat.id, message, "Акции:" + str(message.text)) bot.register_next_step_handler(action.mess, action)
def start(message): print(1) if message.text == '/start': global con, cur spaming.check(message.from_user.id, message.from_user.first_name, message.from_user.last_name, cur, con) selectLang.f = 1 selectLang(message) return 0 print(2) try: if selectLang.f: help(message) return 0 except AttributeError: pass print(3) f = open(fpath + 'files/stikers/logo.webp', 'rb') bot.send_sticker(message.chat.id, f) f.close() keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True) keyboard.add(*[ types.KeyboardButton(name) for name in [ config.text['textPrice'][language[str(message.from_user.id)]], config.text['textActions'][language[str(message.from_user.id)]], config.text['textBalance'][language[str(message.from_user.id)]] ] ]) keyboard.add(*[ types.KeyboardButton(name) for name in [ config.text['contacts'][language[str(message.from_user.id)]], config.text['textLangSel'][language[str(message.from_user.id)]] ] ]) bot.send_message( message.chat.id, '{1}, {0} '.format( message.chat.first_name, config.text['hello'][language[str( message.from_user.id)]]) + u'\U0001F44B\n' + config.text['selInfo'][language[str(message.from_user.id)]], reply_markup=keyboard) botan.track(config.botan_key, message.chat.id, message, 'Старт')
def send_welcome(message): global sub sub = [line.rstrip('\n') for line in open(subfile, 'rt')] if str(message.chat.id) not in sub: with open(subfile, 'a') as f: f.write(str(message.chat.id) + "\n") sub = [line.rstrip('\n') for line in open(subfile, 'rt')] bot.send_message( message.chat.id, "Подписка оформлена, для отключения воспользуйтесь коммандой /unsubscribe", reply_markup=markup_start) botan.track(botan_key, message.chat.id, message, 'Подписка оформлена') bot.send_message(adminid, "Подписка оформлена") else: bot.send_message( message.chat.id, "Подписка уже оформлена. для отключения воспользуйтесь коммандой /unsubscribe", reply_markup=markup_start)
def solve(message): f = open('log.txt', 'a') f.write('\n {}: {} -> {} \n'.format(str(datetime.datetime.now()), message.chat.username, message.text)) f.close() data = message.text.split()[-1].upper() if 'U' and 'R' and 'F' and 'D' and 'L' and 'B' in list(data) and len(data) == 54: out = kociemba.solve(data) bot.reply_to(message, out, reply_markup=markup) bot.reply_to(message, str(len(out.split()))+' steps') botan.track(config.botan_key, message.chat.id, message, 'solve') else: if len(data) > 54: bot.reply_to(message, 'Введены неверные входные данные: Строка содержит > 54 символов', reply_markup=markup) elif len(data) < 54: bot.reply_to(message, 'Введены неверные входные данные: Строка содержит < 54 символов', reply_markup=markup) else: bot.reply_to(message, 'Введены неверные входные данные: Должно быть {U, R, F, D, L, B}', reply_markup=markup)
def any_message(bot, update): """ Print to console and log activity to Botan.io""" print(botan.track(open('botan_token.txt', 'r').read().strip(), update.message.from_user.id, update.message.to_dict(), update.message.text.split(" ")[0])) logger.info("New message\nFrom: %s\nchat_id: %d\nText: %s" % (update.message.from_user, update.message.chat_id, update.message.text))
def start_user(message): botan.track(botan_token, message.from_user.id, {'text':message.text}, message.text) if message.text.replace('/v','') != '': r = requests.get('https://vast-bayou-60079.herokuapp.com/api/search/video?search=' + message.text.replace('/v','')) resMess = r.json() if len(resMess) > 0: if len(resMess) > 5: m = 0 for i in resMess: if m != 6: bot.send_message(message.chat.id,i["text"] + ' \n ' + i["link"]) m = m + 1 else: break else: for i in resMess: bot.send_message(message.chat.id,i["text"] + ' \n ' + i["link"]) else: bot.send_message(message.chat.id,"Sorry, I nothing found") else: bot.send_message(message.chat.id,"Sorry, but I don't search emptiness")
def start(bot, update): bot_user.delete_user(update.message.chat_id) bot_user.new_user(update.message.chat_id) uid = update.message.from_user message_dict = update.message.to_dict() botan.track(botan_token, uid, message_dict, "/start") # bot.sendSticker(chat_id=update.message.chat_id, sticker="BQADAQADHAADyIsGAAFZfq1bphjqlgI") # if bot_user.get_names_len(update.message.chat_id) <= 3: # # bot.sendMessage(update.message.chat_id, # text=BOT_WELCOME) # bot_user.set_state(update.message.chat_id, AWAITING_NAME) # else: # reply_markup = ReplyKeyboardMarkup([[REPLY_MARKUP_SOS, REPLY_MARKUP_ADVICE]], # one_time_keyboard=False, # resize_keyboard=True) bot.sendMessage(update.message.chat_id, text="Напиши 3 варианта своего имени, как к тебе обращаются друзья?") bot_user.set_state(update.message.chat_id, AWAITING_NAME)
def cmd_help(message): bot.send_message(message.chat.id, strings.get(get_language(message.from_user.language_code)).get("help"), parse_mode="HTML") if config.botan_id: botan.track(config.botan_api_key, message.chat.id, message, 'Help') return
def inline(query): results = [ types.InlineQueryResultArticle( id="1", title="Insane password", description="2 prefixes, 2 suffixes, 3 words, separated by the same (random) symbol", input_message_content=types.InputTextMessageContent( message_text=generate_insane_pwd() ), thumb_url="https://raw.githubusercontent.com/MasterGroosha/telegram-xkcd-password-generator/master/img/pwd_green.png", thumb_height=64, thumb_width=64, ), types.InlineQueryResultArticle( id="2", title="Very strong password", description="4 words, random uppercase, separated by numbers", input_message_content=types.InputTextMessageContent( message_text=generate_stronger_pwd() ), thumb_url="https://raw.githubusercontent.com/MasterGroosha/telegram-xkcd-password-generator/master/img/pwd_green.png", thumb_height=64, thumb_width=64, ), types.InlineQueryResultArticle( id="3", title="Strong password", description="3 words, random uppercase, separated by numbers", input_message_content=types.InputTextMessageContent( message_text=generate_strong_pwd() ), thumb_url="https://raw.githubusercontent.com/MasterGroosha/telegram-xkcd-password-generator/master/img/pwd_yellow.png", thumb_height=64, thumb_width=64, ), types.InlineQueryResultArticle( id="4", title="Normal password", description="3 words, second one is uppercase", input_message_content=types.InputTextMessageContent( message_text=generate_normal_pwd() ), thumb_url="https://raw.githubusercontent.com/MasterGroosha/telegram-xkcd-password-generator/master/img/pwd_yellow.png", thumb_height=64, thumb_width=64, ), types.InlineQueryResultArticle( id="5", title="Weak password", description="2 words, no digits", input_message_content=types.InputTextMessageContent( message_text=generate_weak_pwd() ), thumb_url="https://raw.githubusercontent.com/MasterGroosha/telegram-xkcd-password-generator/master/img/pwd_red.png", thumb_height=64, thumb_width=64, ) ] bot.answer_inline_query(inline_query_id=query.id, results=results, cache_time=1, is_personal=True) if config.botan_id: botan.track(config.botan_api_key, -1, {}, 'Inline Mode') return
def run(self, id, args, message_date): self.bot.broadcast_message(id, str(config.get("hello_message"))) botan.track(str(config.get("ya_token")), id, {}, 'HelpCommand')
def cmd_settings(message): bot.send_message(message.chat.id, text=dbworker.get_settings_text(message.chat.id, message.from_user.language_code), reply_markup=make_settings_keyboard_for_user(message.chat.id, message.from_user.language_code), parse_mode="Markdown") if config.botan_id: botan.track(config.botan_api_key, message.chat.id, message, 'Settings') return
def new_kumalak42(message): otpt=''.join(kumalak42()) bot.send_message(message.chat.id,otpt) # Если не нужно собирать ничего, кроме количества использований, замените третий аргумент message на None botan.track(config.botan_key, message.chat.id, message, 'Новый расклад') return
def any_mssg(message): bot.send_message(message.chat.id, "Введите команду /predict") # Если не нужно собирать ничего, кроме количества использований, замените третий аргумент message на None botan.track(config.botan_key, message.chat.id, message, 'прочие сообщения') return
def run(self, id, args, message_date): self.bot.broadcast_message(id, str(get_random_post())) botan.track(str(config.get("ya_token")), id, {}, 'RandomCommand')
def run(self, id, args, message_date): if self.check_status(id, args) == False: botan.track(str(config.get("ya_token")), id, {}, 'SubscribeAutoCommand') channels = config.get("channels"); channel = args[0] if (len(channels) > 1) else channels[0]["name"] self.subscribe(id, channel, Type.Auto, str(config.get("auto_message")))
def execute(self): # Send user statistics to botan print 'Sent user to botan:', botan.track(self.botan_token, self.update['from']['id'], self.update, 'User') if "title" in self.update["chat"]: print 'Sent group to botan:', botan.track(self.botan_token, self.update['chat']['id'], self.update, 'Group') # Write new user, group into database user = self.write_user() self.write_group() # extract command, text, address command = TDO.Update.get_command(self.update) # Train new user (if not in the group) if not user.setdefault('trained', False) and "title" not in self.update["chat"]: user["state"] = user.setdefault("state", "") result = self.tutorial(user, command) return result else: # Execute command if command in self.commands: text = TDO.Update.get_text(self.update, command) words = text.split() if len(words) and words[0].startswith("@") and len(words[0]) > 1: address = words[0][1:] else: address = '' if command in ['list', 'list@todobbot', 'l']: print 'Sent list to botan:', botan.track(self.botan_token, self.update['chat']['id'], self.update, '/list') result = self.list(address) elif command in ['todo', 'todo@todobbot', 't']: print 'Sent todo to botan:', botan.track(self.botan_token, self.update['chat']['id'], self.update, '/todo') result = self.todo(text, address) elif command in ['done', 'done@todobbot', 'd']: print 'Sent done to botan:', botan.track(self.botan_token, self.update['chat']['id'], self.update, '/done') result = self.done(text, address) elif command in ['help', 'start', 'help@todobbot', 'start@todobbot', 'h', 's', 'h@todobbot', 's@todobbot']: result = self.help() elif command in ['completed', 'completed@todobbot', 'c']: result = self.completed(text) elif command in ['all', 'a@todobbot', 'a']: result = self.list_all() elif command in ['tutorial', 'tutorial@todobbot']: if "title" not in self.update["chat"]: user['state'] = '' self.change_user_state(user['user_id'], 'trained', False) result = self.tutorial(user, command) else: result = 'Please, use personal chat with @Todobbot to take tutorial.' elif command in ['feedback', 'feedback@todobbot']: result = self.feedback() elif command.startswith('cheer'): result = self.cheer() elif command.startswith('make'): result = self.make(text) elif command.startswith('for'): result = self.for_f(text) elif command.startswith('over'): result = self.over(text) elif command.startswith('countu'): result = self.count(self.users_db) elif command.startswith('countg'): result = self.count(self.groups_db) elif command.startswith('weather'): result = self.weather(text) elif command.startswith('city'): result = self.get_city(text) elif command.startswith('me'): result = self.get_info() return result
def generate_normal_password(message): bot.send_message(message.chat.id, text=generate_strong_pwd()) if config.botan_id: botan.track(config.botan_api_key, message.chat.id, message, 'Strong password') return
def default(message): bot.send_message(message.chat.id, text=generate_strong_pwd()) if config.botan_id: botan.track(config.botan_api_key, message.chat.id, message, 'Strong password (by rand message)') return
def cmd_generate_weak_password(message): bot.send_message(message.chat.id, generate_weak_pwd()) if config.botan_id: botan.track(config.botan_api_key, message.chat.id, message, 'Weak password') return
def start_user(message): botan.track(botan_token, message.from_user.id, {'text':message.text}, message.text) bot.send_message(message.chat.id, "Hi! I'am Gaserd and i like open source. I have my website - gaserd.com. What are you search? Example: /search facebook api");
#!/usr/bin/env python import botan print botan.track(1111, 1, {'text':2}, 'Search') print botan.track('ab', 1, {'text':2}, 'Search')
def cmd_generate_custom(message): bot.send_message(chat_id=message.chat.id, text=generate_custom(message.chat.id), reply_markup=make_regenerate_keyboard(message.from_user.language_code)) if config.botan_id: botan.track(config.botan_api_key, message.chat.id, message, 'Custom password') return
def regenerate(call): bot.edit_message_text(text=generate_custom(call.from_user.id), chat_id=call.from_user.id, message_id=call.message.message_id, reply_markup=make_regenerate_keyboard(call.from_user.language_code)) bot.answer_callback_query(callback_query_id=call.id) if config.botan_id: botan.track(config.botan_api_key, call.message.chat.id, None, 'Custom password')
def cmd_generate_normal_password(message): bot.send_message(message.chat.id, text=generate_insane_pwd()) if config.botan_id: botan.track(config.botan_api_key, message.chat.id, message, 'Insane password') return