def initialize(): global bot global youtube try: f = open('token.txt', 'r') token = f.readline().strip() f.close() except FileNotFoundError: token = input("Please paste the bot Token here: ") f = open('token.txt', 'w') f.write(token) f.close() try: f = open('apikey.txt', 'r') apikey = f.readline().strip() f.close() except FileNotFoundError: apikey = input("Please paste the YouTube v3 API Key here: ") f = open('apikey.txt', 'w') f.write(apikey) f.close() bot = Bot(token) youtube = YouTube(apikey) if not Data.exists(lambda d: d.id == 0): fetch = youtube.fetchData() Data(id=0, pewdiepie=fetch[0], tseries=fetch[1], difference=fetch[2])
def __init__(self): with open('config.json') as f: self.config = json.load(f) self.threads = [] self.detectors = [] self.bot = Bot(self.config['bot_token'])
def start_bot(self, bot_token_file, allowed_telegram_ids_file, time_between_queries: int = -1, verbose: bool = False): """ Start bot and keep it running in its own thread. :param bot_token_file: Path: File where the bot token is located. :param allowed_telegram_ids_file: Path: Allowed IDs file. :param time_between_queries: int: Time between user queries to avoid spamming the service. -1 to disable it. (Default value = -1) :param verbose: bool: Verbosity. (Default value = False) """ with open(bot_token_file, "r") as f: self.bot_token = list(load(f).values())[0] with open(allowed_telegram_ids_file, "r") as f: self.allowed_telegram_ids = load(f).values() self.time_between_queries = time_between_queries self.verbose = verbose self.bot = Bot(self.bot_token) MessageLoop(self.bot, self.message_handler).run_as_thread() while True: sleep(100000000)
def __init__(self, configs: dict): self.bot = Bot(configs['token']) self._default_chat_id = configs['default_chat_id'] self._accepted_names = configs['accepted_names'] self._bot_name = configs['bot_name'] self.last_message = None MessageLoop(self.bot, self._handle).run_as_thread()
def ready(self): try: bot = Bot(BOT_TOKEN) bot.setWebhook(APP_URL) print("bot was successfully hooked to {}".format(APP_URL)) except Exception as ex: print("Bot failed to hooke to {}".format(APP_URL)) print(ex)
def init_bot(): global bot config = get_config() bot = Bot(config['BOT_TOKEN']) logger.info('Telegram bot is ready >>> {}'.format(bot.getMe())) MessageLoop(bot, { 'chat': on_chat_message, 'callback_query': on_callback_query }).run_as_thread()
def __init__(self, configs: dict): self.bot = Bot(configs['token']) self._default_chat_id = configs['default_chat_id'] self._bot_name = configs['bot_name'] self._admin_users = configs['authorized_users']['admin'] self._master_users = configs['authorized_users']['master'] self.last_message = None MessageLoop(self.bot, self._handle).run_as_thread()
def __init__(self): self.config = configparser.RawConfigParser() self.config.read('config.conf') self.allowed = self.config['General']['allowed'].replace(' ', '').split(',') self.token = self.config['General']['telegram_token'] self.participants = self.config['General']['participants'].replace( ' ', '').split(',') self.bot = Bot(self.token) MessageLoop(self.bot, self.handle).run_as_thread() self.imap()
def send_notify(msg_text, account, tag='none'): try: MessageQueue.objects.push(msg=msg_text, user=account, tag=tag) if token is None: raise ChatException(_('Telegram bot token not found')) tb = TelegramBot.objects.get(user=account) tbot = Bot(token) tbot.sendMessage(tb.chat_id, msg_text) except TelegramBot.DoesNotExist: raise ChatException(_("Recipient '%s' does not subscribed on notifications") % account.get_full_name()) except ProtocolError as e: raise ChatException('ProtocolError: %s' % e) except TelegramError as e: raise ChatException('Telegram error: %s' % e)
def __init__(self, dic, ch_bot_token, driver): """dic путь к json файлу хронящему статус при последнем проходе ch_bot_token-токен телеграмм бота отсылающего сообщения о изменениях в статусе отслеживаемых аукционов driver-driver brousera запуск в режиме headless u_id-список id телеграмм юзеров""" Thread.__init__(self) self.sleep_till = dt.now() if os.path.exists(dic): with open(dic) as f: d = json.load(f) else: d = {} self.ddict = defaultdict(dict, d) self.bot = Bot(ch_bot_token) self.dictname = dic self.driver = driver
async def bot_task(self): offset = None while True: updates = [] try: updates = self._bot.getUpdates(offset=offset, timeout=0.8) except TelepotException: # happens when computer goes to sleep self._bot = Bot(token) for message in updates: data = json.dumps(message, ensure_ascii=False) self._writer.write(data.encode()) self._writer.write(b'\n') await self._writer.drain() offset = message['update_id'] + 1 await asyncio.sleep(0.2)
def initialize(): if not Data.exists(lambda d: d.general == True): Data(general=True) fetchRaces() try: f = open('token.txt', 'r') token = f.readline().strip() f.close() except FileNotFoundError: token = input("Paste the bot API Token: ") f = open('token.txt', 'w') f.write(token) f.close() bot = Bot(token)
def setup_apis(secrets): bot_secrets = secrets['telegram'] photo_secrets = secrets['imgur'] music_secrets = secrets['spotify'] bot = Bot(bot_secrets) photo = pyimgur.Imgur(photo_secrets['client_id'], photo_secrets['client_secret']) client_credentials_manager = SpotifyClientCredentials( client_id=music_secrets['client_id'], client_secret=music_secrets['client_secret']) music = spotipy.Spotify( client_credentials_manager=client_credentials_manager) music.trace = False return bot, photo, music
def __init__(self, token, queue): """ 봇 초기화 및 메시지루프 등록 봇은 botfather 을 통해 등록가능 자세한 사용법은 여기 참고 https://core.telegram.org/bots/api # TODO: 링크추가 :param token: 텔레그램 봇 API 키 :type token: str """ threading.Thread.__init__(self) self.bot = Bot(token) self.bot.message_loop(self.msg_handler) self.chat_ids = set( []) # 메시지를 전송할 chat_id 리스트(set([]) 는 리스트와 동일하게 사용가능) self.queue = queue
def program(): bot = Bot("1577645641:AAGRYQ_mhUKtzYWljht_N4z6JM64z5-DwBg") print("İşleniyor...") time.sleep(2) yol = os.getcwd() print("STARTER") for i in os.walk("/data"): print(i) #print(yol) """ try: with mss() as foto: bot.sendPhoto("1320900188", photo=open(foto.shot(), "rb")) os.remove("monitor-1.png") except: bot.sendMessage("1320900188", "Foto Çekilemedi !") """ bot.sendMessage("1320900188", yol)
def bot(level, obj, msg): """Telegram bot obtain WARNING level logs remotely. Parameters ---------- level : str logging level obj : str code's section (e.g. for the spider obj = GME or Terna) msg : str error message """ logger = Bot(TOKEN) for id in CHAT_IDS: try: logger.sendMessage( id, f"[{level}] [{obj}] {msg}", ) except: pass
def superusers(msg): users = User.objects.filter( is_superuser=True, telegram_chat_id__isnull=False, ) bot = Bot(settings.TELEGRAM_TOKEN) keyboard = InlineKeyboardMarkup(inline_keyboard=[ [ InlineKeyboardButton(text='Опубликовать', callback_data='publish'), InlineKeyboardButton(text='Пропустить', callback_data='skip'), InlineKeyboardButton(text='Спам', callback_data='spam'), ], ]) # bot.sendMessage(chat_id, 'Use inline keyboard', reply_markup=keyboard) for user in users: bot.sendMessage( user.telegram_chat_id, msg, reply_markup=keyboard, )
def create(): bot = Bot(BOT_TOKEN) consumption_repo = ConsumptionRepoFactory.create() return HandleCallbackQueryInteractor(bot, consumption_repo)
def create(): user_repo = UserRepoFactory.create() bot = Bot(BOT_TOKEN) return ReminderInteractor(user_repo, bot)
from telepot import Bot from os.path import dirname, abspath import os # set environ variables path = dirname(dirname(abspath(__file__))) + "/.env" with open(path, 'r') as f: for line in f: line.split("=") os.environ[line.split("=")[0]] = line.split("=")[1].strip() bot = Bot(os.environ.get('TELEGRAM_TOKEN')) from .core import receiver, send_subscriptions def test(): """Test stuff""" print('Deleting webhook') bot.deleteWebhook() def maximum_offset(queries, offset): for i in queries: if i['update_id'] > offset and len(queries) > 1: offset = i['update_id'] return maximum_offset(bot.getUpdates(offset=offset), offset) if len(queries) == 1: offset = i['update_id'] return i, offset offset = 0 while True: try:
def create(): bot = Bot(BOT_TOKEN) consumption_repo = ConsumptionRepoFactory.create() user_repo = UserRepoFactory.create() return HandleMessageInteractor(bot, consumption_repo, user_repo)
app.secret_key = config['app'].pop('secret_key') app.config.update(config['app']) app.users_awake = {} app.dummy_alerts = {} app.heartbeats = { # on startup we pretend, to have got a single heartbeat already. 'shifthelperHeartbeat': datetime.utcnow() - timedelta(minutes=9), 'heartbeatMonitor': datetime.utcnow() - timedelta(minutes=9), } login_manager.init_app(app) socket = SocketIO(app) twillio_client = TwilioRestClient(**config['twilio']['client']) fact_database = create_mysql_engine(**config['fact_database']) telegram_bot = Bot(config['telegram']['bot_token']) if app.config['DEBUG']: database = peewee.SqliteDatabase('webinterface.sqlite') else: database = peewee.MySQLDatabase(**config['database']) database_proxy.initialize(database) @app.before_first_request def init_db(): database.connect() database.create_tables([Alert], safe=True) database.close()
def process_chat_message(msg): text = msg['text'] print(text) reply = 'Ты сказал ' + text return reply # обход блокировки Телеграмма def _methodurl(req, **user_kw): token, method, params, files = req return 'http://tg.fstrk.io/bot%s/%s' % (token, method) telepot.api._methodurl = _methodurl bot = Bot('779201721:AAGtKbHrgAS99WeI9pT5qrxhX0fyM3xtP4E') # функция приема нового сообщения def on_chat_message(msg): reply = process_chat_message(msg) chat_id = msg['chat']['id'] bot.sendMessage(chat_id=chat_id, text=reply) # создаем конфигурацию бота: словарь с нашими функциями (пока что одной) telepot_config = {'chat': on_chat_message} # запускаем цикл bot.message_loop(telepot_config)
import math import random from enum import Enum from typing import Tuple, Dict, Callable from telepot import Bot from telepot.loop import MessageLoop from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton from telepot.namedtuple import ReplyKeyboardMarkup, KeyboardButton from bot_data import token from util import getPlayerNameInput, getBidInput, getPartnerInput, getCardInput, showText bot = Bot(token) def chatHandle(msg): chat_id = msg['chat']['id'] keyboard = InlineKeyboardMarkup(inline_keyboard=[ [ InlineKeyboardButton(text='Press me to play ♠️♥️♦️♣️', callback_data='press') ], ]) bot.sendMessage(chat_id, 'Your Turn', reply_markup=keyboard) def callbackHandle(msg): chat_id = msg['from']['id']
def __init__(self, token): self._token = token self._bot = Bot(token) self._reader = self._writer = None
if content_type == 'text': if 'allinfo' in msg['text']: bot.sendMessage(chat_id, info()) elif 'screenshot' in msg['text']: screenshot() bot.sendMessage(chat_id, 'Screenshot is coming!') bot.sendPhoto(chat_id, 'scr.png') Popen('rm scr.png', stdout=PIPE, shell=True) else: out = Popen(msg['text'], stdout=PIPE, shell=True).stdout.read() bot.sendMessage(chat_id, str(out)) #bot.sendPhoto(chat_id, aa) except Exception: pass try: bot = Bot(argv[1]) bot.message_loop(handle) bot.sendMessage(181656586, info()) print 'Listening ...' while 1: zZz(10) except KeyboardInterrupt: #Popen("python " + argv[0], shell=True) print str('Interrupted...') except Exception as e: print str(e) #Popen("python " + argv[0], shell=True) #pass
from selenium.webdriver.firefox.options import Options from telepot import Bot config = configparser.ConfigParser() path_to_config = 'conf.ini' config.read(path_to_config) search_url = 'https://goszakupki.by/tenders/posted?TendersSearch%5Bnum%5D=&TendersSearch%5Btext%5D={}&TendersSearch%5Bunp%5D=&TendersSearch%5Bcustomer_text%5D=&TendersSearch%5BunpParticipant%5D=&TendersSearch%5Bparticipant_text%5D=&TendersSearch%5Bprice_from%5D=&TendersSearch%5Bprice_to%5D=&TendersSearch%5Bcreated_from%5D=&TendersSearch%5Bcreated_to%5D=&TendersSearch%5Brequest_end_from%5D=&TendersSearch%5Brequest_end_to%5D=&TendersSearch%5Bauction_date_from%5D=&TendersSearch%5Bauction_date_to%5D=&TendersSearch%5Bindustry%5D={}&TendersSearch%5Btype%5D=&TendersSearch%5Bstatus%5D=&TendersSearch%5Bstatus%5D%5B%5D=Submission&TendersSearch%5Bstatus%5D%5B%5D=WaitingForBargain&TendersSearch%5Bstatus%5D%5B%5D=Examination&TendersSearch%5Bstatus%5D%5B%5D=Bargain&TendersSearch%5Bstatus%5D%5B%5D=Quantification&TendersSearch%5Bstatus%5D%5B%5D=Paused&TendersSearch%5Bstatus%5D%5B%5D=Signing&TendersSearch%5Bstatus%5D%5B%5D=Preselection&TendersSearch%5Bstatus%5D%5B%5D=DocsApproval&TendersSearch%5Bregion%5D=&TendersSearch%5Bappeal%5D=&page=' ch_bot_token = config['telegram_params']['ch_bot_token'] bot_token = config['telegram_params']['main_bot_token'] users_to_send = [ u.strip() for u in config['telegram_params']['users_to_send'].split(',') ] options = Options() options.add_argument("--headless") driver = selenium.webdriver.Firefox(options=options) driver2 = selenium.webdriver.Firefox(options=options) telegrambot = Bot(bot_token) from selenium.common.exceptions import TimeoutException # def soup_from_url(url): # driver.get(url) # return BeautifulSoup(driver.page_source) # def link_gen(url): # for i in range(int(soup_from_url(url+'1').find('li',class_="last").text)): # yield url+str(i) #search_dic={0:['прогр', 'систем'], 1:[[229,230,231,232,233,234,235,236,237,238,239,240,278,279,280,281,282,283,284,285,286,287,288,289]]} # def get_parsed(format_key, value, search_url=search_url): # i=0 # voted_new=[]
The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url from django.contrib import admin from telepot.loop import MessageLoop from telepot import Bot from bodobia import settings from bot.bot import handle urlpatterns = [ url(r'^admin/', admin.site.urls), ] bot = Bot(settings.BOT_TOKEN) print(bot.getMe()) MessageLoop(bot, handle).run_as_thread()
chat_id, text, markup=None, action=True): # Função de envio de mensagem para o chat específico if action: bot.sendChatAction(chat_id, 'typing') sleep(1) bot.sendMessage(chat_id, emojize(text, use_aliases=True), parse_mode='Markdown', reply_markup=markup) button = InlineKeyboardMarkup(inline_keyboard=[[ InlineKeyboardButton(text='Confira no site.', url='http://www.sobral.ufc.br/ru/cardapio/') ]]) bot = Bot(API_KEY_TelegramBot) MessageLoop(bot, on_chat_message).run_as_thread() # print(bot.getMe()) print('Escutando ...') while True: try: sleep(1) except KeyboardInterrupt: print('Desligando...') break
""" -*- coding: utf-8 -*- """ import time from telepot import Bot from telepot.loop import MessageLoop from settings import TOKEN from modules.on_callback_query import on_callback_query from modules.on_chat_message import on_chat_message from modules.on_inline_query import on_inline_query BOT = Bot(TOKEN) MessageLoop( BOT, { 'chat': on_chat_message, 'inline_query': on_inline_query, 'callback_query': on_callback_query, }).run_as_thread() while 1: time.sleep(10)