Esempio n. 1
0
def check_how_many_to_mode(bot: telepot.Bot, chat_id: int, username: str,
                           mode: Mode):
    log.debug(
        "checking quantity of words to {mode} and starting the lesson".format(
            mode=mode.name))
    try:
        words_num = count_words_to_mode(username, mode)
        log.info("Words to {mode}: {num}".format(mode=mode.name,
                                                 num=words_num))
    except Exception as e:
        bot.sendMessage(
            chat_id,
            'Cannot count words to {mode} {err}'.format(mode=mode.name, err=e))
        log.error(e)
        raise e

    if words_num > 0:
        keyboard = compose_kbd_start_mode(mode)
        global message_with_inline_keyboard
        log.debug("message: {}".format(message_with_inline_keyboard))
        message_with_inline_keyboard = bot.sendMessage(
            chat_id,
            'There are {num} words to {mode}'
            ''.format(num=words_num, mode=mode.name),
            reply_markup=keyboard)
    else:
        bot.sendMessage(chat_id,
                        'There are no words to {mode}'.format(mode=mode.name))
Esempio n. 2
0
    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'])
Esempio n. 3
0
 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)
Esempio n. 4
0
    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()
Esempio n. 5
0
class MrTeaBot(object):
    def __init__(self, token, uid):
        self.bot = Bot(token)
        self.bot.notifyOnMessage(self.handle_message)

        self.uid = uid
        self.name = None
        self.waiting_for_rank = False

    def ask(self, name, rebrew):
        self.name = name
        self.rebrew = rebrew

        r = ' (rebrewed)' if rebrew else ''

        self.bot.sendMessage(
            self.uid,
            'please rate {}{}'.format(name, r)
        )

        self.waiting_for_rank = True

    def log_rank(self, rank):
        doc = {
            'name': self.name,
            'rebrew': self.rebrew,
            'rank': rank,
            '@timestamp': datetime.utcnow(),
        }

        es.index(index="mr_tea", doc_type='tea_rank', body=doc)

    def get_rank(self, msg):
        rank = int(msg['text'])

        if rank < 1 or rank > 5:
            raise ValueError('rank should be between 1 and 5')

        return rank

    def handle_message(self, msg):
        if not self.waiting_for_rank:
            self.bot.sendMessage(self.uid, 'not waiting for rank')
            return

        try:
            self.log_rank(self.get_rank(msg))
        except Exception as e:
            self.bot.sendMessage(self.uid, 'failed to log rank: {}'.format(e))
            return

        self.bot.sendMessage(
            self.uid,
            'your review of {} tea was logged'.format(self.name)
        )

        self.waiting_for_rank = False
Esempio n. 6
0
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()
Esempio n. 7
0
    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()
Esempio n. 8
0
def warn_to_admin(bot: Bot, msg: str) -> None:
    chat_id = msg['chat']['id']
    user_name = msg['from']['username']
    msg_text = None
    if msg['text'] is not None:
        msg_text = msg['text']

    bot.sendMessage(
        ADMIN_ID, f'{user_name} пытался поговорить с ботом в чате № {chat_id}')
Esempio n. 9
0
    def send_info(self, bot: telepot.Bot) -> None:
        info = info_template % (
            self.id, self.full_name, self.university, self.committee, self.age, self.phone_number, self.school_info,
            self.school_type, self.home_addr, self.has_car, self.known_schools, self.idea) + self.free_times

        for admin in admins:
            try:
                msg_id = bot.sendMessage(admin, info, 'Markdown')['message_id']
                bot.sendDocument(admin, self.file_id, reply_to_message_id=msg_id)
            except:
                pass
Esempio n. 10
0
def alert(bot: Bot, msg: dict) -> None:
    chat_id = msg['chat']['id']
    user_name = msg['from']['username']
    msg_text = None
    if msg.get('text') is not None:
        msg_text = msg['text']

    for _id in WHITE_LIST:
        if _id == chat_id: continue
        bot.sendMessage(_id, f'У {user_name} нет вермени объяснять, алерт!')
    bot.sendMessage(chat_id, 'Сообщение было доставлено!')
Esempio n. 11
0
 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()
Esempio n. 12
0
class Telegram:

    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 _handle(self, msg):
        if msg:
            chat_id = msg['chat']['id']
            first_name = msg['from']['first_name']
            message = str(msg.get('text', ''))
            first_world = message[:len(self._bot_name)] if len(message) > len(self._bot_name) else ''

            print(f"[-] ({chat_id}: ') >> {first_name} sent: {message}")

            if first_world.lower() == self._bot_name:
                message = message[len(self._bot_name):]
                print(f'message to monica >> {message}')
                self._last_message = message.strip().lower()

    def send_photo(self, image, name: str = 'photo.jpg', _type: str = '.JPG', chat_id: int = None):
        if not chat_id:
            chat_id = self._default_chat_id
        self.bot.sendPhoto(chat_id, (name, Buffer(_type=_type, image=image)))

    def send_message(self, text: str, chat_id: int = None):
        if not chat_id:
            chat_id = self._default_chat_id
        try:
            self.bot.sendMessage(chat_id, text)
        except exception.TelegramError:
            print(f'[-] Chat not found: {chat_id}')

    def send_bool_question(self, question: str, chat_id: int = None):
        attempts = 3
        self.last_message = None
        self.send_message(text=question, chat_id=chat_id)
        while attempts > 0:
            if self.last_message:
                attempts -= 1
                if self.last_message in ['sim', 'pode']:
                    return True
                elif self.last_message in ['nao', 'nao pode']:
                    return False
                else:
                    self.send_message(text="Por favor, responda com 'sim' ou 'nao'.", chat_id=chat_id)
                    self.last_message = None
        return False
Esempio n. 13
0
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)
Esempio n. 14
0
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])
Esempio n. 15
0
 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
Esempio n. 16
0
    def __init__(self, token, uid):
        self.bot = Bot(token)
        self.bot.notifyOnMessage(self.handle_message)

        self.uid = uid
        self.name = None
        self.waiting_for_rank = False
Esempio n. 17
0
    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)
Esempio n. 18
0
 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)
Esempio n. 19
0
class Tg2Stdio(object):
    def __init__(self, token):
        self._token = token
        self._bot = Bot(token)
        self._reader = self._writer = None

    async def run(self):
        loop = asyncio.get_event_loop()
        self._reader = await stdin_stream_reader(loop)
        self._writer = await stdout_stream_writer(loop)
        await asyncio.gather(self.reader_task(), self.bot_task())

    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)

    async def reader_task(self):
        while not self._reader.at_eof():
            data = await self._reader.readline()
            if not data:
                break
            await self.handle_local_message(data.decode())
        asyncio.get_event_loop().stop()

    async def handle_local_message(self, data):
        message = json.loads(data)
        if 'text' in message:
            if isinstance(message['text'], list):
                for line in message['text']:
                    if line:
                        self._bot.sendMessage(message['chat_id'], line)
            elif message['text']:
                self._bot.sendMessage(message['chat_id'], message['text'])
Esempio n. 20
0
    def subscribe(self):
        self.bot = Bot(self.token)
        self.bot.notifyOnMessage(self.handle_message)

        while 1:
            for user in get_all_users():
                self.handle_user(user)

            time.sleep(1)
Esempio n. 21
0
def sendTelegramMessage(self, bot_token, chat_id, message, **kwargs):
    try:
        bot = TBot(bot_token)
        return bot.sendMessage(chat_id, message, parse_mode="html", **kwargs)
    except TelegramError:
        import logging
        # Get an instance of a logger
        logger = logging.getLogger(__name__)
        logger.critical('Bad telegram token is set %s' % TOKEN)
    except MaxRetryError as exc:
        res = resetTelegramServer()
        countdown = 10 * 60
        if res:
            countdown = 5
        self.retry(countdown=countdown, exc=exc)
    except Exception as exc:
        countdown = 15 * 60
        self.retry(countdown=countdown, exc=exc)
Esempio n. 22
0
    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
Esempio n. 23
0
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)
Esempio n. 24
0
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
Esempio n. 25
0
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,
        )
Esempio n. 26
0
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)
Esempio n. 27
0
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
Esempio n. 28
0
    def __init__(self, queue):
        self.__bot_token = config['bot_token']
        self.__chat_id = config['chat_id']
        self.__client = TelegramBot(self.__bot_token)

        self.__timezone = config.get('timezone', 0)
        self.__notify_levels = config['notify_levels']
        self.__notify_pokemon = config['notify_pokemon']

        self.__queue = queue
        self.__raids = {}
        self.__messages = {}

        retry_time = 1
        try:
            spawn(self.__run())
            retry_time = 1
        except Exception as e:
            log.exception("Exception during runtime spawn: {}".format(repr(e)))
            retry_time *= 2
            sleep(retry_time)
            pass
Esempio n. 29
0
    def command(self, cmd: str, bot: telepot.Bot) -> bool:
        if cmd == '/start':
            bot.sendMessage(self.id, msg_start)
            return True

        elif cmd == '/main_menu':
            self.state = State.MAIN_MENU
            return True

        elif cmd == '/help':
            bot.sendMessage(self.id, msg_help, reply_markup=rkb_state[self.state.value])
            return False

        elif cmd == '/start NeDd1h0DaRh3m':
            bot.sendMessage(self.id, msg_info)
            self.state = State.FULL_NAME
            return True

        else:
            raise CommandError('Command "%s" is not valid' % cmd)
Esempio n. 30
0
 def create():
     user_repo = UserRepoFactory.create()
     bot = Bot(BOT_TOKEN)
     return ReminderInteractor(user_repo, bot)
Esempio n. 31
0
 def create():
     bot = Bot(BOT_TOKEN)
     consumption_repo = ConsumptionRepoFactory.create()
     return HandleCallbackQueryInteractor(bot, consumption_repo)
Esempio n. 32
0
 def create():
     bot = Bot(BOT_TOKEN)
     consumption_repo = ConsumptionRepoFactory.create()
     user_repo = UserRepoFactory.create()
     return HandleMessageInteractor(bot, consumption_repo, user_repo)
Esempio n. 33
0
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:
Esempio n. 34
0
class BubbyBot(object):
    def __init__(self, token):
        self.token = token
        self.valid_answers = [str(x) for x in xrange(0, 11)]
        self.question = 'How much does it hurt from 1 to 10?'
        self.message_hours = [9, 12, 17, 20, 23]

    def get_next_message_time(self):
        d = datetime.now().replace(minute=0)

        for h in self.message_hours:
            if h > d.hour:
                d = d.replace(hour=h)
                break
        else:
            d = d.replace(hour=self.message_hours[0]) + timedelta(days=1)

        return d

    def subscribe(self):
        self.bot = Bot(self.token)
        self.bot.notifyOnMessage(self.handle_message)

        while 1:
            for user in get_all_users():
                self.handle_user(user)

            time.sleep(1)

    def set_next_msg_time(self, user):
        user.next_msg_time = self.get_next_message_time()
        user.save()

    def handle_user(self, user):
        logging.info(user.next_msg_time)

        if user.next_msg_time is None or user.next_msg_time <= datetime.now():
            self.ask_if_head_hurts(user)
            self.set_next_msg_time(user)

    def greet(self, user):
        self.bot.sendMessage(user['id'], STRINGS.greeting)

    def goodbye(self, user_id):
        self.bot.sendMessage(user_id, STRINGS.goodbye)

    def register_user(self, user):
        add_to_database(user)
        self.greet(user)

    def unregister_user(self, user_id):
        remove_from_database(user_id)
        self.goodbye(user_id)

    def ask_if_head_hurts(self, user):
        show_keyboard = {
            'keyboard': [self.valid_answers],
            'force_reply': True
        }

        try:
            self.bot.sendMessage(user.id, self.question, reply_markup=show_keyboard)
        except TelegramError as e:
            logging.exception('ask if head hurts')

            if e.error_code == 403:
                remove_from_database(user.id)

    def register_answer(self, user, answer):
        logging.info('got answer %d', answer)
        if answer == 0:
            self.bot.sendMessage(user['id'], 'I\'m happy your head doesn\'t hurt!')
        elif answer < 4:
            self.bot.sendMessage(user['id'], 'Are you drinking water?? please drink water!')
        elif answer < 6:
            self.bot.sendMessage(user['id'], 'Drink more water and maybe take a pill? :(')
        elif answer < 9:
            self.bot.sendMessage(user['id'], 'Poor little bubby, take another pill')
        else:
            self.bot.sendMessage(user['id'], 'It\'s time to hit the hospital')

        self.commit_answer_to_database(user, answer)

    def get_stastd_key_for_user(self, user):
        return 'bubby_bot.{}'.format(user['id'])

    def commit_answer_to_database(self, user, answer):
        key = self.get_stastd_key_for_user(user)
        logging.info('statsd %s - %d', key, answer)
        statsd_client.gauge(key, answer)

    def invalid_answer(self, user):
        self.bot.sendMessage(user['id'], STRINGS.invalid_answer)

    def send_stats(self, user, text):
        days = text[6:]

        if not days:
            days = 1

        try:
            days = int(days)
        except ValueError:
            days = 1

        key = self.get_stastd_key_for_user(user)
        r = requests.get(graphite_url.format(user['id'], '-{}days'.format(days)))

        with tempfile.NamedTemporaryFile(suffix='.png') as f:
            f.write(r.content)
            f.flush()
            f.seek(0)
            
            if days == 1:
                last_msg_part = '24 hours'
            else:
                last_msg_part = '{} days'.format(days)

            self.bot.sendMessage(user['id'], 'here you go, last ' + last_msg_part)
            r = self.bot.sendPhoto(user['id'], f)

        print(r)

    def handle_message(self, msg):
        if msg['text'] == '/start':
            self.register_user(msg['from'])
        elif msg['text'] == '/stop':
            self.unregister_user(msg['from']['id'])
        elif msg['text'].startswith('/stats'):
            self.send_stats(msg['from'], msg['text'])
        elif msg['text'] in self.valid_answers:
            self.register_answer(msg['from'], int(msg['text']))
        else:
            self.invalid_answer(msg['from'])