Esempio n. 1
0
 def handleMessages(self, msg, status):
     """
     Handle incoming messages
     """
     
     if status != Skype4Py.cmsReceived:
         return;
     
     #if you are sending to yourself when testing
     if status == "SENDING":
         return
     
     #some skype clients double reply to messages we want to ignore them
     #these messages aren't displayed in UI
     if status == "READ":
         return
     
     chat = msg.Chat
     
     #if it is the first message being sent...
     chat_id = utils.get_chat_id(chat)
     
     if  chat not in self.chats.values():
         self.chats[chat_id] = chat
         pprint("Sending initial message...")
         pprint(self.sendMessage(chat_id, '%sisn\'t here right now, but feel free to talk to me, Cleverbot, in the mean time' 
                              % (self.skype.CurrentUser.FullName), msg.FromHandle))
     else:
         pprint("Asking Cleverbot...")
         response = self.cb.Ask(msg.Body) 
         pprint("Sending Cleverbot's response...")
         pprint(self.sendMessage(chat_id, response, msg.FromHandle))
Esempio n. 2
0
 def _wrapped_fn(bot, updater):
     chat_id = get_chat_id(updater)
     if str(chat_id) in allowed_user_ids:
         return chat_fn(bot, updater, chat_id)
     else:
         bot.send_message(chat_id, text="Access denied")
         return
Esempio n. 3
0
def reply_callback(update: Update, context: CallbackContext):
    message: Message = update.message
    if message.chat_id == CHAT_ID:
        string = str(message)  #[0:-1]
        string = string.replace("\'", '\"')
        string = string.replace("True", '1')
        string = string.replace("False", '0')
        with open('replyid.json', 'w') as outfile:
            outfile.write(string)
        with open('replyid.json') as outfile:
            data = json.load(outfile)
        msg_dict = data['reply_to_message']
        if 'forward_from' in msg_dict:
            msg_username = data['reply_to_message']['forward_from'][
                'first_name']
        else:
            msg_username = data['reply_to_message']['forward_sender_name']
        reply_to_id = get_chat_id(msg_username)
        if message.text is not None:
            TelegramTimedOutRetry(
                retry_count=BOT_RETRIES,
                function=context.bot.send_message,
                function_kwargs={
                    "chat_id": reply_to_id,
                    "text": message.text,
                    "from_chat_id": message.chat_id,
                    "message_id": message.message_id,
                    "timeout": BOT_TIMEOUT,
                },
            ).retry()
        if message.effective_attachment is not None:
            for at in message.ATTACHMENT_TYPES:
                attachment: Union[TelegramObject,
                                  List[TelegramObject]] = getattr(message, at)
                if attachment is not None:

                    params = prepare_params(attachment, at, reply_to_id)
                    if params is None:
                        continue

                    params["timeout"] = BOT_TIMEOUT
                    TelegramTimedOutRetry(
                        retry_count=BOT_RETRIES,
                        function=getattr(context.bot, f"send_{at}"),
                        function_kwargs=params,
                    ).retry()

                    break
    else:
        TelegramTimedOutRetry(
            retry_count=BOT_RETRIES,
            function=context.bot.forward_message,
            function_kwargs={
                "chat_id": CHAT_ID,
                "from_chat_id": message.chat_id,
                "message_id": message.message_id,
                "timeout": BOT_TIMEOUT,
            },
        ).retry()
Esempio n. 4
0
def process_new_message(message_json):
    print('process_new_message')
    chat_id = utils.get_chat_id(message_json)

    if chat_id == config.CryptoShookMaster_ID:

        message = utils.get_message(message_json)
        print('message: {}'.format(message))

        bot.send_message(config.CryptoShook_News_ID,
                         message,
                         parse_mode=telegram.ParseMode.MARKDOWN)

    pass
Esempio n. 5
0
    def __init__(self, message_entity):
        self.user_id = utils.get_sender_id(message_entity)
        self.display_name = utils.sender_name(message_entity)
        self.phone_number = utils.get_phone_number(message_entity)
        self.conversation = message_entity.getFrom()
        self.chat_id = utils.get_chat_id(message_entity)
        self.chat_type = 'group' if message_entity.isGroupMessage() else 'user'
        self.type = message_entity.getMediaType() if utils.is_media_message(
            message_entity) else 'text'
        self.message_entity = message_entity
        self.valid = False
        self.message = ""
        self.text = ""
        self.file_path = None
        self.command = None

        self.build()
Esempio n. 6
0
def check_received_message(new_message_data):
    print(json.dumps(new_message_data, indent=4, sort_keys=True))
    message_text = utils.get_message_text(new_message_data)
    repo.insert(new_message_data)

    chat_id = utils.get_chat_id(new_message_data)

    if utils.starts_with(message_text, "/banter"):
        send_audio(chat_id, message_text)

    if utils.starts_with(message_text, "/"):


        if message_text == '/subit':
            send_message_with_styles(chat_id, cmds.subway())
        elif message_text == '/inside':
            send_message_with_styles(chat_id, cmds.inside())
        elif message_text == '/matti':
            send_message_with_styles(chat_id, cmds.matti())
        elif message_text == '/donald':
            send_message_with_styles(chat_id, cmds.donald())
        elif message_text == '/help' or message_text == '/apua':
            send_message_with_styles(chat_id, cmds.help())
Esempio n. 7
0
def send_welcome(message):
    data['id'] = message.chat.id

    bot.send_message(chat_id=message.chat.id, text='Здравствуйте. Введите своё Имя.')
    bot.register_next_step_handler(message=message, callback=process_phone_step)
    hash_key = get_chat_id(chat_id=data['id'], postfix='profile')
# Adds an option of running the bot in debug mode right from a console:
# `$ python3 main.py --debug`  OR  `$ python3 main.py -d`
parser = argparse.ArgumentParser()
parser.add_argument("-d",
                    "--debug",
                    help="runs bot in debug mode",
                    action="store_true")
args = parser.parse_args()
if args.debug:
    bot_token = tokens.bot_test  # set your token in .bashrc (see tokens.py)
    chat_name = "@pybegtest"
    r = redis.StrictRedis(host="localhost")
    url = f"postgresql://{db_user}:{db_password}@{db_host}:{db_port}/{db_name}"
    print("Running bot in debug mode")

# Automatically gets required ids depending on chat_name
from utils import get_admins, get_chat_id

chat_id = get_chat_id(chat_name)
admin_ids = get_admins(chat_name)
nometa = """
Пожалуйста, не задавайте мета-вопросов в чате!
Мета-вопрос - это вопрос, который подразумевает другие вопросы.
http://nometa.xyz/
"""
captcha_message = """
Привет, {names}!\n
Пожалуйста подтверди, что ты человек. 
Если ты не сделаешь этого в течении {seconds} секунд, я буду вынужден прогнать тебя из чата.
"""