I'm currently developing a live chat application that integrates web and Telegram users through a socket connection. While messages sent from the web interface to Telegram users are successfully delivered, I'm encountering issues when trying to capture incoming messages from Telegram. Despite the live chat setup, messages originating from Telegram do not seem to be captured by my system. I'm seeking guidance on how to effectively intercept and process these incoming Telegram messages. Any insights or advice on troubleshooting this issue would be greatly appreciated.
@bot.message_handler(func=lambda message: True)
def store_message(message):
if message.text.startswith('/'):
return
message_text = message.text
username = message.from_user.username
sender = message.from_user.id
# Fetch the active session for this sender
session = db.instance.find_one({"user_id": sender, "is_active": True,})
if session:
session_id = session["session_id"]
ticket_id = session["ticket_id"] # Ensure that the ticket_id is stored in the session document
# Create the message document to insert into the database
message_document = {
"ticket_id": ticket_id,
"session_id": session_id, # Include the ticket_id in the message document
"text": message_text,
"sender": username,
"sender_type": "user",
"user_id":sender,
"last_interaction": datetime.utcnow()
}
db.messages.insert_one(message_document)
print(f"About to emit message to room {ticket_id}: {message_text}")
last_interaction = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
socketio.emit('message_from_telegram', {
'ticket_id': ticket_id,
'message': message_text,
'sender': sender,
'last_interaction': last_interaction
})
print(f"Emitted message: {message_text}")
bot.reply_to(message, 'Message Sent')
# Update the last interaction timestamp
db.messages.update_one({"session_id": session_id}, {"$set": {"last_interaction": datetime.utcnow()}})
else:
# No active session found for this user
bot.reply_to(message, 'No active session found. Please start a new session.')
Script code
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.0/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect('https://' + document.domain + ':' + location.port);
socket.on('connect', function () {
console.log('Websocket connected!');
const ticketId = document.getElementById('file-upload-data').getAttribute('ticket-id');
console.log('Joining room:', ticketId); // Ensure this logs the correct ticket ID
socket.emit('join', { room: ticketId });
});
socket.on('message_from_telegram', function (msg) {
console.log("Received 'message_from_telegram'", msg);
appendMessage(msg);
});
// Handler for 'message_response' events (as before)
socket.on('message_response', function (msg) {
console.log("Received 'message_response':", msg);
appendMessage(msg);
});
socket.on('join_confirmation', function (msg) {
console.log(msg.message); // It should log 'You have joined room XYZ'
});
// Handler for 'message_from_user' events
// Function to append messages to the chat area
function appendMessage(msg) {
const chatArea = document.querySelector('.flex-grow.overflow-y-auto.mb-4');
const messageElement = document.createElement('div');
messageElement.className = 'message mb-4 p-4 bg-gray-50 rounded-md shadow';
messageElement.innerHTML = `
<div class="text-sm">
<span class="font-semibold">${msg.sender}:</span>
${msg.message}
<span class="block text-xs text-gray-400">${msg.last_interaction}</span>
</div>
`;
chatArea.appendChild(messageElement);
chatArea.scrollTop = chatArea.scrollHeight; // Scroll to the bottom
}
const form = document.getElementById('chat-form');
form.addEventListener('submit', function (e) {
e.preventDefault();
const messageInput = document.querySelector('#chat');
const message = messageInput.value;
const ticketId = document.getElementById('file-upload-data').getAttribute('ticket-id');
sendMessage(ticketId, message);
messageInput.value = ''; // Clear the input field
});
function sendMessage(ticket_id, message) {
console.log('Sending message:', message, 'to ticket:', ticket_id); // Add this line for debugging
socket.emit('send_message', { ticket_id: ticket_id, message: message });
}
</script>
Initially, I attempted to create a room based on the ticket ID and emit all messages to that room, but this approach was unsuccessful. Subsequently, I set the broadcast option to true, hoping it would resolve the issue, but to no avail.