Esempio n. 1
0
import telepot
import re
import urllib3
from telepot.loop import OrderedWebhook

bot = telepot.Bot('1034101496:AAE6imsI-sOEea4LPjVV4_nJoq3-0UB5xmI')

def handle(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    print(content_type, chat_type, chat_id)

    if content_type == 'text':
        pattern=re.search(r'^\*(.*)', msg['text'])
        if pattern:
            bot.sendMessage(-1001149714028, pattern.group(1))

webhook = OrderedWebhook(bot, handle)

webhook.run_as_thread()
Esempio n. 2
0
        return printByTag(text)
    elif command == "/read" or command == "read":
        return printById(text)
    elif text.split(" ")[0].lower() == "/date" or text.split(" ")[0].lower() == "date":
        return notesByDate(text)
    else:
        return printHelp()

# Main starts here
token = str(os.environ["telegram_token"])
myChat_id = int(os.environ["telegram_chat_id"])
bot = telepot.Bot(token) # Bot is created from the telepot class
app = Flask(__name__)
URL = str(os.environ["telegram_url"])
webhook = OrderedWebhook(bot, {'chat': on_chat_message,
                               'callback_query': on_callback_query,
                               'inline_query': on_inline_query,
                               'chosen_inline_result': on_chosen_inline_result})

@app.route('/', methods=['GET', 'POST'])
def pass_update():
    webhook.feed(request.data)
    return 'OK'

if __name__ == '__main__':
    app.run()
    printf("Executed the run")
    
if __name__ != '__main__':
    try:
        bot.setWebhook(URL)
    # Sometimes it would raise this error, but webhook still set successfully.
Esempio n. 3
0
TOKEN = sys.argv[1]
# uses the second argument as the port the server will run on
# note: Telegram requires bots be run on port 443, 80, 88, or 8443
PORT = int(sys.argv[2])
# the third argument is the url that Telegram will send data to
URL = sys.argv[3]

# set up basic flask server
app = Flask(__name__)
# set up telegram bot using given token
bot = telepot.Bot(TOKEN)
# delete any existing webhook
bot.deleteWebhook()
# creates webhook, using handle function to handle chat messages
webhook = OrderedWebhook(bot, {
    'chat': handle,
})


# uses Flask to accept Telegram GET and POST requests at /webhook
@app.route("/webhook", methods=['GET', 'POST'])
def get_data():
    webhook.feed(request.data)
    return 'OK'


if __name__ == '__main__':
    # initializes webhook, passing the cert public key file
    bot.setWebhook(URL, certificate=open('./cert/certificate.pem'))
    # runs the webhook continuously in the background
    webhook.run_as_thread()
Esempio n. 4
0
    u(32),
    u(33),
    2,  # clear 29,30, skip 28
    u(31),  # clear 31,32,33
    u(39),
    u(36),
    2,
    u(37),
    7,  # clear 36,37,39
    u(28),  # discard
    u(38),  # discard
    u(40),  # return
]


def handle(msg):
    print msg


bot = telepot.Bot('abc')
webhook = OrderedWebhook(bot, handle)

webhook.run_as_thread(maxhold=8)

for update in sequence:
    if type(update) is dict:
        webhook.feed(update)
        time.sleep(1)
    else:
        time.sleep(update)
Esempio n. 5
0
    bot.answerInlineQuery(query_id, articles)

# need `/setinlinefeedback`
def on_chosen_inline_result(msg):
    result_id, from_id, query_string = telepot.glance(msg, flavor='chosen_inline_result')
    print('Chosen Inline Result:', result_id, from_id, query_string)


TOKEN = sys.argv[1]
PORT = int(sys.argv[2])
URL = sys.argv[3]

app = Flask(__name__)
bot = telepot.Bot(TOKEN)
webhook = OrderedWebhook(bot, {'chat': on_chat_message,
                               'callback_query': on_callback_query,
                               'inline_query': on_inline_query,
                               'chosen_inline_result': on_chosen_inline_result})

@app.route('/webhook', methods=['GET', 'POST'])
def pass_update():
    webhook.feed(request.data)
    return 'OK'

if __name__ == '__main__':
    try:
        bot.setWebhook(URL)
    # Sometimes it would raise this error, but webhook still set successfully.
    except telepot.exception.TooManyRequestsError:
        pass

    webhook.run_as_thread()
Esempio n. 6
0
    u(33),
    2,  # clear 29,30, skip 28
    u(31),  # clear 31,32,33

    u(39),
    u(36),
    2,
    u(37),
    7,  # clear 36,37,39

    u(28),  # discard
    u(38),  # discard

    u(40),  # return
]

def handle(msg):
    print msg

bot = telepot.Bot('abc')
webhook = OrderedWebhook(bot, handle)

webhook.run_as_thread(maxhold=8)

for update in sequence:
    if type(update) is dict:
        webhook.feed(update)
        time.sleep(1)
    else:
        time.sleep(update)
Esempio n. 7
0
Line_Config.read("./LineSection/Config.ini")

#===================Telegram Section======================
#Telegram Bot Entity
Global_Element.Tg_Bot = telepot.Bot(Tg_Config["TELEGRAM"]["ACCESS_TOKEN"])


#處理Telegram訊息
@WebApp.route('/Telegram', methods=["POST"])
def Telegram_Handler():
    BotHook.feed(request.data)
    return '200 OK'


BotHook = OrderedWebhook(
    Global_Element.Tg_Bot,
    Tg_Bot_Client.Telegram_MessageHandler.Telegram_MessageReceive)

#======================LINE Section=========================
#LINE Entity
Global_Element.Line_Bot = LineBotApi(
    Line_Config["line-bot"]["channel_access_token"])
Global_Element.Line_Hookhandler = WebhookHandler(
    Line_Config["line-bot"]["channel_secret"])


#處理LINE訊息
@WebApp.route('/LINE', methods=["POST"])
def LINE_Handler():
    Body = request.get_data(as_text=True)
    LINE_MessageHandler.LINE_MessageReceive(Body)
Esempio n. 8
0
    interaction = Interaction(user=user,
                              msg_s=chat_text,
                              msg_r=msg_r,
                              msg_pk=msg_pk,
                              btns=button_list,
                              start_time=current_time)
    interaction.save()

    user.last_node = element
    print('user last node save: ', element.name)
    user.save()


bot = telepot.Bot(TOKEN)

webhook = OrderedWebhook(bot, {'chat': on_chat_message})
webhook.run_as_thread()
logger = logging.getLogger('bot')


def index(request):
    try:
        bod = request.body
        bod = bod.decode("utf-8")
        logger.info(bod)
        bod = json.loads(bod)

        logger.info('req')
        on_chat_message(bod)
        # webhook.feed(bod)
    except ValueError:
Esempio n. 9
0
    def on_chat_message(self, msg):
        self._count += 1
        self.sender.sendMessage(self._count)


TOKEN = sys.argv[1]
PORT = int(sys.argv[2])
URL = sys.argv[3]

app = Flask(__name__)

bot = telepot.DelegatorBot(TOKEN, [
    pave_event_space()(per_chat_id(), create_open, MessageCounter, timeout=10),
])

webhook = OrderedWebhook(bot)


@app.route('/webhook', methods=['GET', 'POST'])
def pass_update():
    webhook.feed(request.data)
    return 'OK'


if __name__ == '__main__':
    try:
        bot.setWebhook(URL)
    # Sometimes it would raise this error, but webhook still set successfully.
    except telepot.exception.TooManyRequestsError:
        pass
Esempio n. 10
0
        # inline_keyboard = []
        # for categoria in response:
        #     inline_keyboard.append([InlineKeyboardButton(text=categoria['fields']['name'], callback_data=categoria['pk'])])

        # keyboard = InlineKeyboardMarkup(inline_keyboard=inline_keyboard)
        # bot.sendMessage(chat_id, 'Categorías:', reply_markup=keyboard)


app = Flask(__name__)
bot = telepot.DelegatorBot(TOKEN, [
    include_callback_query_chat_id(pave_event_space())(
        per_chat_id(), create_open, ChatSesion, timeout=100),
])
bot.message_loop(source=UPDATE_QUEUE)
webhook = OrderedWebhook(bot)


@app.route('/bot' + TOKEN, methods=['GET', 'POST'])
def pass_update():
    UPDATE_QUEUE.put(request.data)
    return 'ok'


try:
    bot.setWebhook()
except telepot.exception.TooManyRequestsError:
    pass

try:
    bot.setWebhook(URL + SECRET)
Esempio n. 11
0
                            parse_mode='Markdown')

    elif data[0] == 'joycasino':
        if data[1] == 'generate':
            bot.answerCallbackQuery(query_id, 'OK')
            bot.sendMessage(from_id, 'Напиши сумму🤑')
            query[from_id].append('joycasino_amount')


TOKEN = '860594921:AAG1GHkdaJU0JFlExy-6CNJUSeeIYcyTo4c'
URL = 'https://opitniynaebator.herokuapp.com/'

app = Flask(__name__)
bot = telepot.Bot(TOKEN)
webhook = OrderedWebhook(bot, {
    'chat': on_chat_message,
    'callback_query': on_callback_query
})


@app.route('/', methods=['GET', 'POST'])
def pass_update():
    webhook.feed(request.data)
    return 'OK'


@app.route('/message', methods=['GET'])
def pass_message():
    for admin in ADMINS:
        bot.sendMessage(admin, request.args.get('message'))
    return 'OK'