Telegram Bot integration Messagees
All checks were successful
continuous-integration/drone/push Build is passing
All checks were successful
continuous-integration/drone/push Build is passing
This commit is contained in:
parent
30b8efac2f
commit
bc7a8c5625
@ -0,0 +1,34 @@
|
|||||||
|
# Generated by Django 5.0.3 on 2025-05-20 08:04
|
||||||
|
|
||||||
|
import django.db.models.deletion
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('pxy_bots', '0005_remove_telegrambot_assistant_id_and_more'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.CreateModel(
|
||||||
|
name='TelegramConversation',
|
||||||
|
fields=[
|
||||||
|
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||||
|
('user_id', models.CharField(max_length=64)),
|
||||||
|
('started_at', models.DateTimeField(auto_now_add=True)),
|
||||||
|
('bot', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='conversations', to='pxy_bots.telegrambot')),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
migrations.CreateModel(
|
||||||
|
name='TelegramMessage',
|
||||||
|
fields=[
|
||||||
|
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||||
|
('direction', models.CharField(choices=[('in', 'In'), ('out', 'Out')], max_length=4)),
|
||||||
|
('content', models.TextField()),
|
||||||
|
('timestamp', models.DateTimeField(auto_now_add=True)),
|
||||||
|
('response_time_ms', models.IntegerField(blank=True, null=True)),
|
||||||
|
('conversation', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='messages', to='pxy_bots.telegramconversation')),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
]
|
@ -45,3 +45,40 @@ class TelegramBot(models.Model):
|
|||||||
return response.json()
|
return response.json()
|
||||||
else:
|
else:
|
||||||
raise ValueError(f"Failed to set webhook for {self.name}: {response.json()}")
|
raise ValueError(f"Failed to set webhook for {self.name}: {response.json()}")
|
||||||
|
|
||||||
|
|
||||||
|
from django.db import models
|
||||||
|
|
||||||
|
class TelegramConversation(models.Model):
|
||||||
|
bot = models.ForeignKey(
|
||||||
|
'TelegramBot',
|
||||||
|
on_delete=models.CASCADE,
|
||||||
|
related_name='conversations'
|
||||||
|
)
|
||||||
|
user_id = models.CharField(max_length=64)
|
||||||
|
started_at = models.DateTimeField(auto_now_add=True)
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return f"{self.user_id} @ {self.started_at:%Y-%m-%d %H:%M}"
|
||||||
|
|
||||||
|
class TelegramMessage(models.Model):
|
||||||
|
IN = 'in'
|
||||||
|
OUT = 'out'
|
||||||
|
DIRECTION_CHOICES = [
|
||||||
|
(IN, 'In'),
|
||||||
|
(OUT, 'Out'),
|
||||||
|
]
|
||||||
|
|
||||||
|
conversation = models.ForeignKey(
|
||||||
|
TelegramConversation,
|
||||||
|
on_delete=models.CASCADE,
|
||||||
|
related_name='messages'
|
||||||
|
)
|
||||||
|
direction = models.CharField(max_length=4, choices=DIRECTION_CHOICES)
|
||||||
|
content = models.TextField()
|
||||||
|
timestamp = models.DateTimeField(auto_now_add=True)
|
||||||
|
response_time_ms = models.IntegerField(null=True, blank=True)
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return f"[{self.direction}] {self.content[:30]}…"
|
||||||
|
|
||||||
|
@ -7,6 +7,9 @@ from .models import TelegramBot
|
|||||||
from pxy_langchain.services import LangchainAIService
|
from pxy_langchain.services import LangchainAIService
|
||||||
from .handlers import dream_city_command, start, help_command, handle_location
|
from .handlers import dream_city_command, start, help_command, handle_location
|
||||||
import logging
|
import logging
|
||||||
|
from .models import TelegramConversation, TelegramMessage, TelegramBot
|
||||||
|
from django.utils import timezone
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@ -21,6 +24,22 @@ async def telegram_webhook(request, bot_name):
|
|||||||
# Step 1: Fetch the bot instance asynchronously
|
# Step 1: Fetch the bot instance asynchronously
|
||||||
try:
|
try:
|
||||||
bot_instance = await sync_to_async(TelegramBot.objects.get)(name=bot_name, is_active=True)
|
bot_instance = await sync_to_async(TelegramBot.objects.get)(name=bot_name, is_active=True)
|
||||||
|
# Step 1.5: get_or_create de la conversación
|
||||||
|
user_id = str(update.effective_user.id)
|
||||||
|
conv, _ = await sync_to_async(TelegramConversation.objects.get_or_create)(
|
||||||
|
bot=bot_instance,
|
||||||
|
user_id=user_id,
|
||||||
|
defaults={'started_at': timezone.now()}
|
||||||
|
)
|
||||||
|
|
||||||
|
# Step 1.6: guardar mensaje entrante
|
||||||
|
incoming_text = update.message.text or ""
|
||||||
|
await sync_to_async(TelegramMessage.objects.create)(
|
||||||
|
conversation=conv,
|
||||||
|
direction=TelegramMessage.IN,
|
||||||
|
content=incoming_text
|
||||||
|
)
|
||||||
|
|
||||||
logger.info(f"Loaded bot configuration: {bot_instance}")
|
logger.info(f"Loaded bot configuration: {bot_instance}")
|
||||||
except TelegramBot.DoesNotExist:
|
except TelegramBot.DoesNotExist:
|
||||||
logger.error(f"Bot '{bot_name}' not found or inactive.")
|
logger.error(f"Bot '{bot_name}' not found or inactive.")
|
||||||
|
Loading…
x
Reference in New Issue
Block a user