59 lines
1.7 KiB
Python
59 lines
1.7 KiB
Python
import time
|
|
|
|
import pika
|
|
import requests
|
|
from loguru import logger
|
|
|
|
|
|
def _send_message_to_user(bot_token, target_id, message):
|
|
base_url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
|
|
params = {
|
|
"chat_id": target_id,
|
|
"text": message,
|
|
"parse_mode": "MarkdownV2"
|
|
}
|
|
max_retry = 3
|
|
retry_count = 0
|
|
while retry_count < max_retry:
|
|
response = requests.post(base_url, params=params)
|
|
if response.status_code == 200:
|
|
logger.debug(f'消息发送成功:{message}')
|
|
return # 如果发送成功,立即返回
|
|
else:
|
|
logger.debug('消息发送失败,重试中...')
|
|
logger.error(response.text)
|
|
time.sleep(10)
|
|
retry_count += 1
|
|
|
|
logger.debug('消息发送失败')
|
|
|
|
|
|
# 你的消息发送逻辑
|
|
|
|
class MessageServer:
|
|
def __init__(self):
|
|
self.credentials = pika.PlainCredentials('bot', 'xiaom@i123')
|
|
self.connection = pika.BlockingConnection(
|
|
pika.ConnectionParameters('45.89.233.249', 5672, '/', credentials=self.credentials))
|
|
self.channel = self.connection.channel()
|
|
self.channel.queue_declare(queue='message_queue')
|
|
|
|
def start(self):
|
|
try:
|
|
def callback(ch, method, properties, body):
|
|
logger.info(body.decode())
|
|
bot_token, target_id, message = body.decode().split('|')
|
|
_send_message_to_user(bot_token, target_id, message)
|
|
|
|
self.channel.basic_consume(queue='message_queue', on_message_callback=callback, auto_ack=True)
|
|
self.channel.start_consuming()
|
|
except Exception as e:
|
|
logger.error(e)
|
|
|
|
def stop(self):
|
|
self.connection.close()
|
|
|
|
|
|
server = MessageServer()
|
|
server.start()
|