def initBot(self): botRequest = None if self.CONFIG['bot']['proxy'] is not None: botRequest = telegram.utils.request.Request( con_pool_size = 10, proxy_url=self.CONFIG['bot']['proxy'], connect_timeout=120, read_timeout=1200) self.bot = TelegramBot(self.CONFIG['bot']['token'], botRequest=botRequest)
def main(): configparser.read(sys.argv[1]) init_logger(configparser) bot = TelegramBot(configparser, logger) bot.message_loop() logger.info("Bot " + bot.getMe()['first_name'] + " started") # Keep the program running. while 1: time.sleep(10)
def bot_runner(thread_statuses, q_offer, bot_settings_file, bot_configs_dir): """ Function creates a Telegram Bot and supplies it with offers from q_offer queue. :param thread_statuses: used for debugging and checking up on threads :param q_offer: offers which are supplied to the bot :param bot_settings_file: settings file path :param bot_configs_dir: configs directory path """ # Starting the bot thread_statuses[current_thread().name] = "Booting" try: bot = TelegramBot(bot_settings_file, bot_configs_dir) except Exception as err: thread_statuses[current_thread().name] = "Error -- %s" % err.__str__() return bot.start() while not current_thread().is_stopped(): thread_statuses[current_thread().name] = "Waiting" while q_offer.qsize() > 0: # Get an offer and update status thread_statuses[current_thread().name] = "Work %02d" % q_offer.qsize() offer = q_offer.get() # Process the offer (and send it if that's needed bot.process_offer(offer) bot.stop() thread_statuses[current_thread().name] = "Stopped"
from bot import TelegramBot as Bot from components import Message, BotCommand from meme import give_me_meme bot = Bot(config='config.py') def send_reply(message): if not message: return 'Due to some problem I was not able to read your message! Please try again' if message.animation is not None: return 'U send a animation' if message.audio is not None: return 'U send a audio' if message.video is not None: return 'U send a video' if message.document is not None: return 'U send a document' if message.sticker is not None: return 'u send a sticker' if message.photo is not None: return 'u send a photo' return message.text def execute_command(bot_command): if bot_command.command == '/meme': memes = give_me_meme(bot_command.discription) for meme in memes: bot.sendPhotoMessage(meme,chat_id=message.from_.id) elif bot_command.command == '/do': bot.sendTextMessage(message= f'kaam krtwa reh din bhar',chat_id=message.from_.id) update_id = -1 while True:
import datetime import logging import os import mpd import redis import requests from bot import TelegramBot TOKEN = os.environ.get("TELEGRAM_TOKEN") bot = TelegramBot(TOKEN) MPD_PASSWORD = os.environ.get("MPD_PASSWORD") MPD_HOST = os.environ.get("MPD_HOST", "localhost") MPD_PORT = os.environ.get("MPD_POST", 6600) YEELIGHT_BASE_URL = os.environ.get("YEELIGHT_BASE_URL") redisconn = redis.Redis() def time_format(timestamp): dt = datetime.datetime.fromtimestamp(timestamp) return dt.strftime('%Y-%m-%d %H:%M:%S') def get_mpd_client(): mpd_client = mpd.MPDClient() mpd_client.connect(MPD_HOST, MPD_PORT) if MPD_PASSWORD:
def main(): TelegramBot('####:####')
from flask import request from bot import TelegramBot app = Flask(__name__) app.config.from_envvar("CONFIG_FILE") logger = logging.getLogger() logger.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') handler = logging.StreamHandler(stream=sys.stdout) handler.setFormatter(formatter) logger.addHandler(handler) bot = TelegramBot(app.config['TOKEN']) logger.propagate = False app.route('/bot-webhook') def webhook(): update = request.get_json() bot.process_update(update) return dict(status='ok') if __name__ == '__main__': me = bot.me() logger.info("Bot named %(first_name)s/%(username)s" % me['result']) app.logger.addHandler(handler) app.run(host="0.0.0.0")
app.config.from_envvar("CONFIG_FILE") logger = logging.getLogger() logger.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') if app.config.get('LOG_FILE', None): handler = logging.FileHandler(app.config['LOG_FILE']) else: handler = logging.StreamHandler(stream=sys.stdout) handler.setFormatter(formatter) logger.addHandler(handler) app.logger.addHandler(handler) bot = TelegramBot(app.config['TOKEN']) logger.propagate = False @app.route("/test") def index(): return "it's working, it's workiiiiing" @app.route('/', methods=['POST']) def webhook(): update = request.get_json() bot.process_update(update) return 'ok'
ssl_context.load_verify_locations(SCANNER["cert_file"]) ssl_context.check_hostname = False subnet_filters = SCANNER.get("subnets", None) scanner = RouterOsScanner(INTERVAL, SCANNER['address'], SCANNER["username"], SCANNER["password"], ssl_context, subnet_filters) else: raise ValueError( "Unknown scanner type. Should be one of ['arping', 'routeros_api']" ) scanner.set_new_device_alert(new_device_alert) bot = TelegramBot(TOKEN, BotMainState) bot.allow_chat(ADMIN_CHAT) print("Starting bot...") bot.start() print("Bot started") print("Starting scanner...") scanner.start() print("Scanner started") try: while True: sleep(300) except KeyboardInterrupt as e: print("Interrupted")
handler.setFormatter(logFormatter) logger = logging.getLogger('Logger') logger.setLevel(logging.INFO) logger.addHandler(handler) logger.info('Start main') logger.info('Load config') config = configparser.ConfigParser() config.read('motion-sensor.ini') pool = multiprocessing.Pool(processes=3) m = multiprocessing.Manager() camQueue = m.Queue() botQueue = m.Queue() logger.info('Init cam') cam = CamThread(3, "Camera", config, logger, camQueue, botQueue) cam.start() logger.info('Init motion sensor') pirThread = PirThread(1, "PirThread", config, logger) pirThread.start() logger.info('Init bot') telegramBot = TelegramBot(1, "Bot", config, logger, pirThread, cam, botQueue) telegramBot.start() cam.addBot(telegramBot) pirThread.addBot(telegramBot) logger.info('Init complete')
from config import Config from yandex_webhook import YandexWebhook from alice_handler import AliceHandler app = Flask(__name__) config = Config() via_webhook = True if via_webhook is False: # для телеграм бота from bot import TelegramBot telegram_bot = TelegramBot(token=config.telegtam_token, via_polling=True) telegram_dispatcher = telegram_bot.get_dispatcher() else: # для вебхуков Алисы from plugins import animego from plugins import mal from cast import Cast from mal2alice import Mal2Alice import time site = animego.Site() print('Caching mal...') mal2alice = Mal2Alice(mal, site) print('Finding chromecasts...') cast = Cast()
from bot import TelegramBot import yaml with open("config/config.yml", 'r') as ymlfile: cfg = yaml.load(ymlfile, Loader=yaml.FullLoader) bot = TelegramBot(cfg['token']) bot.start() bot.stop()
from flask import Flask, jsonify from bot import TelegramBot from config import TELEGRAM_INIT_WEBHOOK_URL from ticket_bot import search_tickets from apscheduler.schedulers.background import BackgroundScheduler app = Flask(__name__) TelegramBot.init_webhook(TELEGRAM_INIT_WEBHOOK_URL) @app.route('/', methods=['GET']) def index(): return jsonify(message="Server is running") @app.route('/webhook', methods=['POST']) def telegram_post(): print("New webhook request") return {"message": "Request from telegram is processed"} cron = BackgroundScheduler(daemon=True) cron.add_job(search_tickets, 'interval', hours=12, kwargs={ 'min_days': 3, 'max_days': 7, 'departure_months': [4], 'departure_days': [1]
from bot import TelegramBot if __name__ == '__main__': bot = TelegramBot() bot.run()
from bot import TelegramBot from random import randint bot_ob = TelegramBot("config.cfg") def check_message_contents(msg): """ Determines if the message variable is correct response :param msg: :return: String var ok or Prompt response """ if msg == "y" or msg == "n": return 'ok' else: return 'Response needs to be either "y" or "n"' def generate_img(all_content_list): """ Generate a random number between 1 - 616196 and append to url to get frame :return: String var URL to get frame of video """ frame_rand = randint(1, 61696) # keep looping until frame_rand is not in all_content_list while frame_rand in all_content_list: frame_rand = randint(1, 61696) url = 'https://framex-dev.wadrid.net/api/video/Falcon%20Heavy%20Test%20Flight%20(' \ 'Hosted%20Webcast)-wbSwFU6tY1c/frame/' + str(frame_rand) return url, frame_rand
from time import time, sleep from generator import Generator from bot import TelegramBot print 'TELEGRAM CHAT SIMULATOR' logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) generator = Generator() tokens = {} with open('config.json') as c: j = json.load(c) tokens = j['tokens'] bots = {} for u in generator.users: start = time() print 'Initializing %s bot' % u bots[u] = TelegramBot(tokens[u]) print 'Bot initialized (%.2f s)' % float(time() - start) for i in range(10): (msg, diff, user) = generator.getMessage() print 'Next message in %d seconds' % diff sleep(diff) b = bots[user] b.sendMessage(msg)
app.config.from_envvar("CONFIG_FILE") logger = logging.getLogger() logger.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') if app.config.get('LOG_FILE', None): handler = logging.FileHandler(app.config['LOG_FILE']) else: handler = logging.StreamHandler(stream=sys.stdout) handler.setFormatter(formatter) logger.addHandler(handler) app.logger.addHandler(handler) bot = TelegramBot(app.config['TOKEN']) logger.propagate = False @app.route("/test") def index(): return "it's working, it's workiiiiing" @app.route('/', methods=['POST']) def webhook(): update = request.get_json() bot.process_update(update) return 'ok' if __name__ == '__main__': me = bot.me()
from bot import TelegramBot bot = TelegramBot("config.cfg") def make_reply(msg): reply = None if msg is not None: reply = 'Okay' return reply update_id = None while True: updates = bot.get_updates(offset=update_id) updates = updates["result"] if updates: for item in updates: update_id = item["update_id"] try: message = str(item["message"]["text"]) except: message = None from_ = item["message"]["from"]["id"] reply = make_reply(message) bot.send_message(reply, from_)
import subprocess import shlex from flask import Flask, request, jsonify from config import TELEGRAM_INIT_WEBHOOK_URL as webhook, WEBHOOK_HOSTNAME as hostname from bot import TelegramBot app = Flask(__name__) if not TelegramBot.init_webhook(webhook): try: raise RuntimeError finally: print("Webhook not initialized properly") @app.route("/webhook", methods=["POST"]) def index(): res = request.get_json() robot = TelegramBot() robot.parseData(res) isSuccessful = robot.conditionalResponse() return jsonify(success=isSuccessful) def webhookProccess(hostname): shCommand = "ssh -o ServerAliveInterval=60 -R {}:80:localhost:8888 serveo.net".format( hostname) args = shlex.split(shCommand) subprocess.Popen(args)
import os import requests from bottle import Bottle, response, request as bottle_request from bot import TelegramBot if __name__ == '__main__': app = TelegramBot() app.run(host="localhost", port="5000") ## Used for running locally # app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 5000))) ## used for running on Heroku
def index(): res = request.get_json() robot = TelegramBot() robot.parseData(res) isSuccessful = robot.conditionalResponse() return jsonify(success=isSuccessful)
class TgHentaiBot(object): def __init__(self, config): self.CONFIG = config self.initDb() self.initBot() self.initEHentaiDownloader() self.initTelegraph() def initTelegraph(self): self.telegraph = HentaiTelegraph(self.CONFIG['telegraph']['token'], proxy=self.CONFIG['telegraph']['proxy']) def initEHentaiDownloader(self): self.hentaiDownloader = EHentaiDownloader(self.CONFIG['ehentai']['cookies_file'], self.CONFIG['ehentai']['archer_dir'], self.CONFIG['ehentai']['proxy']) def initDb(self): if self.CONFIG['database']['type'].upper() == 'POSTGRESQL': self.db = HentaiPgDb(self.CONFIG['database']['host'], self.CONFIG['database']['database'], self.CONFIG['database']['user'], self.CONFIG['database']['password'],) if self.CONFIG['database']['type'].upper() == 'SQLITE': self.db = HentaiSqliteDb(self.CONFIG['database']['path']) def initBot(self): botRequest = None if self.CONFIG['bot']['proxy'] is not None: botRequest = telegram.utils.request.Request( con_pool_size = 10, proxy_url=self.CONFIG['bot']['proxy'], connect_timeout=120, read_timeout=1200) self.bot = TelegramBot(self.CONFIG['bot']['token'], botRequest=botRequest) def addUrls(self, matchUrls, urls=None): if urls is None: urls = list(map(lambda tmp: tmp[0], matchUrls)) inUrls = list(map(lambda tmp: tmp['url'], self.db.has_urls(urls))) noInUrls = list(filter(lambda url: (url[0] not in inUrls), matchUrls)) for url in noInUrls: res = self.db.get_url(url=url[0]) if len(res) == 0: self.db.add_url(url[0], url[1], url[2], url[3]) def doUpdates(self): maxUpdateId = self.db.get_max_update_id() if IS_DEBUG: logger.debug('maxUpdateId: {}'.format(maxUpdateId)) updates = self.bot.get_updates(maxUpdateId + 1) for update in updates: logger.info('Handle update id: {}'.format(update.update_id)) if update.channel_post is not None and update.channel_post.chat.type == 'channel' and update.channel_post.chat.id == self.CONFIG['bot']['chat_id'] and update.channel_post.text is not None: matchUrls = get_hentai_url_from_text(update.channel_post.text) if len(matchUrls) != 0: urls = list(map(lambda tmp: tmp[0], matchUrls)) res = self.db.get_msg(update_id=update.update_id) if len(res) == 0: self.db.add_msg(update.update_id, update.channel_post.message_id, update.channel_post.chat.id, update.channel_post.text, urls) self.addUrls(matchUrls, urls) def doSingleDownloadUrl(self, urlData): pageUrl = urlData['url'] logger.info('Download url:{}'.format(pageUrl)) info = self.hentaiDownloader.download(pageUrl) if info is None: return None self.db.set_downloaded_url(pageUrl, info['title'], info['path']) return info def doDownload(self): datas = self.db.get_undownloaded() for data in datas: hasDlErr = 0 updateId = data['update_id'] for urlData in data['url_array']: if urlData is None: matchUrls = get_hentai_url_from_text(data['orig_chat_text']) self.addUrls(matchUrls) continue elif urlData['downloaded']: continue info = self.doSingleDownloadUrl(urlData) if info is None: hasDlErr = hasDlErr + 1 if hasDlErr == 0: self.db.set_downloaded_msg(updateId) def compressImage(self, inputFile, targetSize=5*1024*1024, step=5, quality=100): im = Image.open(inputFile) if os.path.getsize(inputFile) >= (targetSize-1024): while quality>0: imgIO = BytesIO() im.save(imgIO, 'jpeg', quality=quality) if imgIO.tell() < (targetSize-1024): im.save(inputFile, 'jpeg', quality=quality) break quality = quality - step def unzip(self, zipFilePath, unZipDir): logger.info('Start unzip file: {}'.format(zipFilePath)) with zipfile.ZipFile(zipFilePath) as existing_zip: existing_zip.extractall(unZipDir) def upImageDirToTelegraph(self, imageDir): logger.info('Upload image dir: {}'.format(imageDir)) uploadFiles = os.listdir(imageDir) uploadFiles = natsorted(uploadFiles) uploadFiles = list(map(lambda file: imageDir+'/'+file, uploadFiles)) # removeFiles = [] for uploadFile in uploadFiles: fileSize = os.path.getsize(uploadFile) if int(fileSize/1024) > (5*1024-1): self.compressImage(uploadFile) # removeFiles.append(uploadFile) urls = [] if len(uploadFiles) > 20: up_size = len(uploadFiles) part = 20 temp_pos = 0 while temp_pos != None : new_pos = temp_pos + part if new_pos >= up_size: new_pos = None newUploadFiles = uploadFiles[temp_pos: new_pos] temp_urls = upload_file(newUploadFiles, self.CONFIG['telegraph']['proxy']) urls.extend(temp_urls) temp_pos = new_pos else: urls = upload_file(uploadFiles, self.CONFIG['telegraph']['proxy']) return urls def upTelegraphPage(self, title, pathTitle, imageUrls): logger.info('Upload telegraph page path: {} title: {}'.format(pathTitle, title)) telegraphContent = '' for imageUrl in imageUrls: telegraphContent = telegraphContent + '<img src="'+imageUrl+'">' pageRes = self.telegraph.create_page(pathTitle, html_content='None') pageRes = self.telegraph.edit_page(pageRes['path'], title, html_content=telegraphContent) return pageRes def doSingleUpload(self, urlData): pageUrl = urlData['url'] title = urlData['title'] filePath = urlData['filepath'] logger.info('Start upload file: {} url: {}'.format(filePath, pageUrl)) telegraphTitle = str(self.CONFIG['bot']['chat_id']) + '-' + urlData['domain'] + '-' + urlData['hentai_id_1'] + '_' + urlData['hentai_id_2'] unZipDir, ext = os.path.splitext(filePath) try: self.unzip(filePath, unZipDir) urls = self.upImageDirToTelegraph(unZipDir) shutil.rmtree(unZipDir) if IS_DELETE_ARCHIVER: try: os.remove(filePath) except Exception as delErr: logger.info('Delete file error: {} file: '.format(repr(e), filePath)) createRes = self.upTelegraphPage(title, telegraphTitle, urls) logger.info(createRes) self.db.set_uploaded_url(pageUrl, 'https://telegra.ph/{}'.format(createRes['path'])) return createRes except Exception as e: logger.info('Upload Error: {}'.format(repr(e))) return None def doUpload(self): datas = self.db.get_unuploaded() hasErr = 0 logger.debug('Satrt Upload: {}'.format(datas)) for data in datas: updateId = data['update_id'] for urlData in data['url_array']: if urlData is not None and urlData['uploaded']: continue res = self.doSingleUpload(urlData) if res == None: hasErr = hasErr + 1 if hasErr == 0: self.db.set_uploaded_msg(updateId) def doEdit(self): datas = self.db.get_unedited(); logger.debug('Satrt Edit: {}'.format(datas)) for data in datas: updateId = data['update_id'] chatId = data['chat_id'] msgId = data['message_id'] originText = data['orig_chat_text'] urlReps = [] for urlData in data['url_array']: sourceUrl = urlData['url'] telegraphUrl = urlData['telegraph_url'] title = urlData['title'] urlReps.append({ 'title': title, 'source': sourceUrl, 'neo': telegraphUrl, 'domain': urlData['domain'] }) logger.info('Edit msg updateId: {} msgId: {} '.format(updateId, msgId)) data = self.bot.edit_hentai_to_telegraph(chat_id=chatId, message_id=msgId, origin_text=originText, url_datas=urlReps) self.db.set_edited(updateId, data)
import time import signal from threading import Thread import threading import pathFinder from bot import TelegramBot import sys import os # Fix pathing issues with Windows sys.path.insert(1, '../SchoolPathFinder') bot = TelegramBot() def exit_gracefully(signum, frame): # restore the original signal handler as otherwise evil things will happen # in raw_input when CTRL+C is pressed, and our signal handler is not re-entrant signal.signal(signal.SIGINT, original_sigint) # restore the exit gracefully handler here sys.exit() def UpdateQueuePosition(bot, one, chat_id=None, item=None): """This function will send a message to the user telling him what his position in the queue is Args: bot (TelegramBot): Please refer to bot.py one (bool): If send to only one user chat_id (int, optional): Chat id of user to send to. Defaults to None.
from config import Config from bot import TelegramBot from time import sleep BOT_URL = "https://api.telegram.org/bot" TOKEN = Config.ASKME_BOT_TOKEN new_bot = TelegramBot(BOT_URL, TOKEN) def main(): while True: answer = new_bot.get_message() if answer is not None: chat_id = answer["chat_id"] text = answer["text"] if text == "/start": print(new_bot.send_message(chat_id, "Hello, i'm AskMeBot")) elif text == "hi": print(new_bot.send_message(chat_id, text)) else: print(new_bot.send_message(chat_id, "How can i help you!")) else: continue sleep(3) if __name__ == "__main__": main()
from bot import TelegramBot my_bot = TelegramBot() msg = """ *JUST CREATED A TELEGRAM BOT* *AUTHOR:* LENNY *LANGUAGE:* PYTHON *MESSAGE:* I AM AWESOME """ my_bot.send_message(msg=msg, chat_id=681966513)