Exemplo n.º 1
0
def hello():
    global chat
    TOKEN = "303253879:AAGlGdiEJhIO933iVpJg2-tiRJwhpqC4o6g"

    requests.get('https://api.telegram.org/bot%s/sendMessage?chat_id=%s&text=ok' % (TOKEN, chat.chat_id))
    print(request.json)
    msg = Message(request.json)
    chat = Chat(msg.chat_id)

    if msg.chat_id in UNVERIFIED_USERS:

        login = msg.text
        try:
            user = User.get(login)
            user.chat_id = chat.chat_id
            user.update()
            UNVERIFIED_USERS.remove(msg.chat_id)
            chat.sendmessage("Вы добавлены в рассылку!")
        except:
            chat.sendmessage("No such user!!")
            msg.text = '/start'

    if msg.text == '/start':
        chat.sendmessage("Введите Ваш логин:")
        UNVERIFIED_USERS.append(msg.chat_id)

    elif msg.text == 'VK':
        text = "Parser result for VK"
        login = ChatInfo.getlogin(msg.chat_id)
        user = User.get(login)
        subs = user.subscriptions
        if subs is not None:
            chat.sendmessage(str(subs))
        else:
            chat.sendmessage("Ваши подписки")

        json_keyboard = json.dumps({'keyboard': [["VK"], ["Instagram"]],
                                    'one_time_keyboard': False,
                                    'resize_keyboard': True})
        bot.getKeyboard(msg.chat_id, text, json_keyboard)

    elif msg.text == 'Instagram':
        text = "Parser result for Instagram"

        json_keyboard = json.dumps({'keyboard': [["VK"], ["Instagram"]],
                                    'one_time_keyboard': False,
                                    'resize_keyboard': True})

        bot.getKeyboard(msg.chat_id, text, json_keyboard)

    else:
        json_keyboard = json.dumps({'keyboard': [["VK"], ["Instagram"]],
                                    'one_time_keyboard': False,
                                    'resize_keyboard': True})

        bot.getKeyboard(msg.chat_id, "Choose source!", json_keyboard)
        print(request.json)
Exemplo n.º 2
0
def sendif(t, ms_params):
    global recv_prev

    if recv_prev:
        return

    if t == None:
        recv_prev = True
    else:
        for i in t.split('|'):
            if eq(i, recv_msg.text):
                recv_prev = True
                break

    if recv_prev == True:
        for i in ms_params:
            send(recv_user, Message(*i))
Exemplo n.º 3
0
    def __init__(self, bot, chat_id, text, message_id, user_firstname=''):
        # Get user object from SQL
        conn = sqlhandler.getConnection()
        cur = conn.cursor()
        select_user_query = """SELECT userID, chatID, name, expectedMsgType, tempParams, wantsMenu, course, 
		wantsLecturePlan, address, wantsTransportInfo, wantsToRateMeals, menuPushTime, lecturePushTime, 
		pauseAllNotifications, wantsExamWarning FROM users WHERE chatID = %s """
        cur.execute(select_user_query, (chat_id, ))
        userSqlRow = cur.fetchall()
        conn.commit()
        user = usr.User(chat_id)
        newUser = False
        if cur.rowcount == 1:
            user = sqlconverter.getUser(userSqlRow[0])
        elif cur.rowcount > 1:
            logging.warning('More than one user with chatID %s found!',
                            chat_id)
            user = sqlconverter.getUser(userSqlRow[0])
        else:
            logging.info('Creating new user for chatID %s.', chat_id)
            newUser = True
        cur.close()

        # Write firstName from telegram into user object
        user.telegram_firstName = user_firstname

        # Process message
        try:
            message = msg.Message(user, text, message_id)

            if '🥃' in message.text:
                bot.sendMessage(message.user.chatID,
                                'WHISKEEEEEYYYYYY!!! 🥃🥃🥃')

            if message.isCommand:
                cmd.Command(message, bot, conn).findCommand()
            else:
                cmd.Command(message, bot, conn).interpretMessage()
        except:
            e = sys.exc_info()
            exc_type, exc_value, exc_traceback = sys.exc_info()
            stack = traceback.extract_tb(exc_traceback)
            logging.warning(
                "An error occured handling the following message: %s. Error: %s, Stacktrace: %s",
                text, e, stack)
            bot.sendMessage(
                chat_id,
                "An error occured while trying to fulfill your request. If this keeps happening,"
                +
                " please file a bug report via /reportbug, create an issue on GitHub under"
                +
                " https://github.com/Mueller-Patrick/dhbw_service_bot or send a message to @P4ddy_m"
            )
            bot.sendMessage(os.environ['PATRICK_TELEGRAM_ID'], (
                "The bot encountered an error.\nSender: {}\nMessage received: {}\nError: {}\nStack: {}"
                .format(user_firstname, text, e, stack)))

        # Save user object to SQL
        cur = conn.cursor()
        if newUser:
            print("new")
            insert_user_query = """INSERT INTO users (chatID, name, telegram_firstName, expectedMsgType, tempParams, wantsMenu, course, 
			wantsLecturePlan, address, wantsTransportInfo, wantsToRateMeals, menuPushTime, lecturePushTime, 
			pauseAllNotifications, lastMessage, wantsExamWarning) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, now(), %s) """
            cur.execute(insert_user_query,
                        sqlconverter.getUserInsertTuple(user))
        else:
            print("Update")
            update_user_query = """UPDATE users SET name = %s, telegram_firstName = %s, expectedMsgType = %s, tempParams = %s, wantsMenu = %s, 
			course = %s, wantsLecturePlan = %s, address = %s, wantsTransportInfo = %s, wantsToRateMeals = %s, 
			menuPushTime = %s, lecturePushTime = %s, pauseAllNotifications = %s, lastMessage = now(), wantsExamWarning = %s WHERE userID = %s """
            cur.execute(update_user_query,
                        sqlconverter.getUserUpdateTuple(user))

        conn.commit()
        cur.close()
        conn.close()