如何不断更新来自不同来源的值?

2024-06-03 12:24:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个电报机器人,它从postgresSQL和google电子表格中获取值。但是,当我运行它时,只从这个源获取静态值。但我需要不断更新它们

片段:

import pandas as pd
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import telebot
from telebot import types
import psycopg2

bot = telebot.TeleBot("TOKEN")

scope = ['https://spreadsheets.google.com/feeds',
         'https://www.googleapis.com/auth/drive']

#--------------Getting Spreadsheet Values
creds = ServiceAccountCredentials.from_json_keyfile_name('.json', scope)
client = gspread.authorize(creds)
sh = client.open('SPREADSHEET')
sheet2 = sh.worksheet("WORKSHEET")
coordinates = sheet2.col_values(5)
arrive = sheet2.col_values(6)
unit = sheet2.col_values(1)

#--------------Getting PostgreSQL Values
connection = psycopg2.connect(user="USER",
                              password="PASSWORD",
                              host="HOST",
                              port="PORT",)
cursor = connection.cursor()
query = "SELECT * FROM TABLE"
cursor.execute(query)
ds = pd.read_sql(query, connection)
unit_s = ds['name']
engine_state = ds["engine_state"]
reverse_geo = ds["reverse_geo"]
speed = ds["speed_miles_per_hour"]

#--------------Def for replying Telebot
def value(type):
   unique_index = pd.Index(unit)
   m = unique_index.get_loc(type)
   arr = arrive[m]
   number = unit[m]
   info1 = status[m]
   geo = reverse_geo[m]
   final = str(f"UNIT : {number}\nSTATUS : {info1}\nENGINE STATE : 
               {engine}\nDEPART LOCATION : {info2}\nCURRENT LOCATION : {geo})
   return final

 #--------------Keyboard Markup
 num1 = unit[:16]
 num2 = unit[16:]
 markup = telebot.types.ReplyKeyboardMarkup(row_width=3)
 for i,n in zip(num1,num2):
     txt = str(i)
     mxt = str(n)
     markup.row(txt,mxt)
 @bot.message_handler(commands=['start'])
 def start_message(message):
     bot.send_message(message.chat.id, 'Hello U Wrote Me /start', 
 reply_markup=markup)

 @bot.message_handler(content_types=['text'])
 def send_text(message):
     response = message.text.lower()
     response1 = str(response)
     text = value(response)
     if message.text.lower() == str(response):
         bot.send_message(message.chat.id, str(text))
     elif message.text.lower() != '':
         bot.send_message(message.chat.id, 'NaN')
 bot.delete_webhook()
 bot.polling()

我尝试使用threding专门获取电子表格值和SQl值 但我没有弄明白如何将线程与其他def值一起使用


Tags: textimportsendmessageresponsedefbotds