P
P
Proritsatel2020-06-22 14:17:32
Python
Proritsatel, 2020-06-22 14:17:32

How to send data on button click in python telegram bot?

Hello!
I have a code that sends data through a telegram bot to a telegram group using an API key

import OpenOPC
import time
import requests
###################################################
react_temp = int(input("Введите температуру слоя реактора (целое число): "))
r_tmp_lim = int(input("Введите допустимое отклонение температур реактора (+- x градусов, целое число): "))
###################################################
def send_telegram(text: str):
    token = "1854430581:AAFupZdsev5kfmwKDLe9OPdwan210gX0p4o"
    url = "https://api.telegram.org/bot"
    channel_id = "@newOilPlant"
    url += token
    method = url + "/sendMessage"

    r = requests.post(method, data={
         "chat_id": channel_id,
         "text": text
          })
    if r.status_code != 200:
        raise Exception("post_text error")
###################################################
opc = OpenOPC.client()
servers = opc.servers()
opc.connect("Owen.OPCNet.DA.1")
print("Удачное подключение к " + servers[0])
#--------------------------------------------------------------------------------------------------------#
tagsValue = [];
# Тр-ра Верх
tagsValue.append(opc.list("COM4.TRM_202(adr=104)T_слой_Ср_р-ра.Оперативные параметры")[3])

while True:
    print("-----------------------------------------------------------------------------------------")
    try:
        ############################################################
        # Проверка температур слоя реактора
        val = opc.read(tagsValue, update=1, include_error=True)
        if int(val[0][1]) > (react_temp + r_tmp_lim) or int(val[1][1]) > (react_temp + r_tmp_lim) or int(val[2][1]) > (react_temp + r_tmp_lim):
            try:
                #print("here")
                send_telegram("Слой реактора перегрет до {0:.2f} {1:.2f} {2:.2f} С".format(val[0][1], val[1][1], val[2][1]))
            except:
                print("Включите VPN (test 1)")
        if int(val[0][1]) < (react_temp - r_tmp_lim) or int(val[1][1]) < (react_temp - r_tmp_lim) or int(val[2][1]) < (react_temp - r_tmp_lim):
    except:
        print("error read item")
    time.sleep(20)
opc.close()
#---------------------------#

This code is already using a bot. I wanted to make the bot have a menu and when the /get_data command is called from the bot, for example, a button appears and I can send data from the main script to the user's dialogue with the bot.
It turns out that either the code with the button or the main program works for me.
import telebot
token = "1203397890:AAF3Z53lbtmCWkXlsxJl4fXRj6Dtcv6TEc0"

bot = telebot.TeleBot(token)

@bot.message_handler(commands=['start'])
def start_message(message):
    keyboard = telebot.types.ReplyKeyboardMarkup(True)
    bot.send_message(message.chat.id, 'Привет!', reply_markup=keyboard)

@bot.message_handler(commands=['get_data'])
def get_data(message):
    markup = telebot.types.InlineKeyboardMarkup()
    markup.add(telebot.types.InlineKeyboardButton(text='Получить данные', callback_data=3))
    bot.send_message(message.chat.id, text="Что вы хотите сделать?", reply_markup=markup)

@bot.callback_query_handler(func=lambda call: True)
def query_handler(call):
    #bot.answer_callback_query(callback_query_id=call.id, text='Спасибо за честный ответ!')
    answer = ''
    if call.data == '3':
        answer = '...Тут будут данные...'
    bot.send_message(call.message.chat.id, answer)

bot.polling()

If I add bot.polling(), only the dialogue with the bot works for me, if I remove bot.polling(), then the main code works for me, but the bot does not work.
How to solve this problem?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Proritsatel, 2020-06-26
@Proritsatel

I redid my code as advised by a colleague from above. Added two threads and it worked

opc = OpenOPC.client()
servers = opc.servers()
opc.connect("Owen.OPCNet.DA.1")
print("Удачное подключение к " + servers[0])
#--------------------------------------------------------------------------------------------------------#
tagsValue = [];
# Тр-ра Верх
tagsValue.append(opc.list("COM4.TRM_202(adr=104)T_слой_Ср_р-ра.Оперативные параметры")[3])

def send_mess():
    while True:
    print("-----------------------------------------------------------------------------------------")
    try:
        ############################################################
        # Проверка температур слоя реактора
        val = opc.read(tagsValue, update=1, include_error=True)
        if int(val[0][1]) > (react_temp + r_tmp_lim) or int(val[1][1]) > (react_temp + r_tmp_lim) or int(val[2][1]) > (react_temp + r_tmp_lim):
            try:
                #print("here")
                send_telegram("Слой реактора перегрет до {0:.2f} {1:.2f} {2:.2f} С".format(val[0][1], val[1][1], val[2][1]))
            except:
                print("Включите VPN (test 1)")
        if int(val[0][1]) < (react_temp - r_tmp_lim) or int(val[1][1]) < (react_temp - r_tmp_lim) or int(val[2][1]) < (react_temp - r_tmp_lim):
    except:
        print("error read item")
    time.sleep(20)
    opc.close()
#---------------------------#

thrd_send_mess = threading.Thread(target=send_mess)
thrd_send_mess.start()

thrd_run_setting = threading.Thread(target=run_setting)
thrd_run_setting.start()

D
del4pp, 2020-06-22
@del4pp

Because you have an eternal loop in your code (While True).
If you want both this and that to work, you need to create a function, put the code in it

###################################################
opc = OpenOPC.client()
servers = opc.servers()
opc.connect("Owen.OPCNet.DA.1")
print("Удачное подключение к " + servers[0])
#--------------------------------------------------------------------------------------------------------#
tagsValue = [];
# Тр-ра Верх
tagsValue.append(opc.list("COM4.TRM_202(adr=104)T_слой_Ср_р-ра.Оперативные параметры")[3])

while True:
    print("-----------------------------------------------------------------------------------------")
    try:
        ############################################################
        # Проверка температур слоя реактора
        val = opc.read(tagsValue, update=1, include_error=True)
        if int(val[0][1]) > (react_temp + r_tmp_lim) or int(val[1][1]) > (react_temp + r_tmp_lim) or int(val[2][1]) > (react_temp + r_tmp_lim):
            try:
                #print("here")
                send_telegram("Слой реактора перегрет до {0:.2f} {1:.2f} {2:.2f} С".format(val[0][1], val[1][1], val[2][1]))
            except:
                print("Включите VPN (test 1)")
        if int(val[0][1]) < (react_temp - r_tmp_lim) or int(val[1][1]) < (react_temp - r_tmp_lim) or int(val[2][1]) < (react_temp - r_tmp_lim):
    except:
        print("error read item")
    time.sleep(20)
opc.close()
#---------------------------#

and run the function in a thread ( Threads )
The code is executed from top to bottom, and without bot.poling, the code stops on an eternal loop, if you use bot.poling - the program works on the handler

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question