tools-pyqt/src/core/message_client.py
2024-02-29 20:42:57 +08:00

35 lines
1.1 KiB
Python

import pika
class MessageClient:
def __init__(self):
self.credentials = pika.PlainCredentials('bot', 'xiaomi@123')
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 __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
def send_message(self, bot_token, target_id, message):
self.channel.basic_publish(exchange='', routing_key='message_queue', body=f'{bot_token}|{target_id}|{message}')
def close(self):
self.connection.close()
def send_message(bot_token, target_id, message):
with MessageClient() as client:
client.send_message(bot_token, target_id, escape_markdown(message))
def escape_markdown(text):
escape_chars = ['_', '[', ']', '(', ')', '~', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!']
for char in escape_chars:
text = text.replace(char, '\\' + char)
return text