I am writing a code in python that calls a postgresql trigger that detects each new record entered into a table and sends a message to a telegram channel, the problem is that apparently the trigger does not detect the entry of records to the table. table, when entering one it does not give any message, I have made several modifications and nothing. How can I test if it is a code or Postgresql server problem? Can you see the code and give me some ideas. thank you.
Postgresql Code
<code>-- Crear un canal para las notificaciones
CREATE OR REPLACE FUNCTION notify_new_product() RETURNS TRIGGER AS $$
BEGIN
PERFORM pg_notify('nuevos_productos', NEW.oid::text);
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
-- Asociar la función a la tabla productos_precios_historico
CREATE TRIGGER new_product_trigger
AFTER INSERT ON productos_precios_historico
FOR EACH ROW
EXECUTE FUNCTION notify_new_product();
</code>
<code>-- Crear un canal para las notificaciones
CREATE OR REPLACE FUNCTION notify_new_product() RETURNS TRIGGER AS $$
BEGIN
PERFORM pg_notify('nuevos_productos', NEW.oid::text);
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
-- Asociar la función a la tabla productos_precios_historico
CREATE TRIGGER new_product_trigger
AFTER INSERT ON productos_precios_historico
FOR EACH ROW
EXECUTE FUNCTION notify_new_product();
</code>
-- Crear un canal para las notificaciones
CREATE OR REPLACE FUNCTION notify_new_product() RETURNS TRIGGER AS $$
BEGIN
PERFORM pg_notify('nuevos_productos', NEW.oid::text);
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
-- Asociar la función a la tabla productos_precios_historico
CREATE TRIGGER new_product_trigger
AFTER INSERT ON productos_precios_historico
FOR EACH ROW
EXECUTE FUNCTION notify_new_product();
python code
<code>import telebot
import select
import psycopg2
from psycopg2 import sql
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
from datetime import datetime, timedelta
import time
PSYCOPG_DEBUG=1
# Token del bot de Telegram
TOKEN = 'ddd'
# ID del chat donde enviar los mensajes
CHAT_ID = '-1002208074761'
# Configuración de la conexión a PostgreSQL
DATABASE = "tienda"
USER = "postgres"
PASSWORD = "password"
client_encoding='utf8'
# Conexión a PostgreSQL
conn = psycopg2.connect(database="tienda", user="postgres", password="12345", client_encoding='utf8', host='localhost', port='5432',async_=False )
# Crear objeto bot
bot = telebot.TeleBot(TOKEN)
# Función para enviar mensaje a Telegram
def enviar_mensaje(texto):
bot.send_message(CHAT_ID, texto)
# Función para monitorear la tabla y enviar mensajes
def monitorear_tabla():
# Mantener la conexión abierta para recibir notificaciones
#conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
print('aca')
# Crear un objeto para escuchar notificaciones
cur = conn.cursor()
cur.execute("LISTEN nuevos_productos")
print("Esperando nuevas notificaciones...")
while True:
print("Calling poll()")
state = conn.poll()
print(state)
if conn.poll():
print("aca3")
while conn.notifies:
for notify in conn.notifies:
print(f"Received notification: {notify.payload}")
oid = int(notify.payload)
# Consultar el nuevo registro en la tabla
cur.execute("SELECT * FROM productos_precios_historico WHERE oid = %s", (oid,))
producto = cur.fetchone()
if producto:
# Formatear el mensaje a enviar
mensaje = f"Nuevo producto añadido:nn"
mensaje += f"SKU: {producto[1]}n"
mensaje += f"Precio normal: {producto[2]}n"
mensaje += f"Precio internet: {producto[3]}n"
mensaje += f"Precio 4: {producto[4]}n"
# Enviar el mensaje
enviar_mensaje(mensaje)
conn.notifies.clear()
else:
print("No notifications received.")
time.sleep(1)
# Iniciar el monitoreo de la tabla
if __name__ == "__main__":
monitorear_tabla()
</code>
<code>import telebot
import select
import psycopg2
from psycopg2 import sql
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
from datetime import datetime, timedelta
import time
PSYCOPG_DEBUG=1
# Token del bot de Telegram
TOKEN = 'ddd'
# ID del chat donde enviar los mensajes
CHAT_ID = '-1002208074761'
# Configuración de la conexión a PostgreSQL
DATABASE = "tienda"
USER = "postgres"
PASSWORD = "password"
client_encoding='utf8'
# Conexión a PostgreSQL
conn = psycopg2.connect(database="tienda", user="postgres", password="12345", client_encoding='utf8', host='localhost', port='5432',async_=False )
# Crear objeto bot
bot = telebot.TeleBot(TOKEN)
# Función para enviar mensaje a Telegram
def enviar_mensaje(texto):
bot.send_message(CHAT_ID, texto)
# Función para monitorear la tabla y enviar mensajes
def monitorear_tabla():
# Mantener la conexión abierta para recibir notificaciones
#conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
print('aca')
# Crear un objeto para escuchar notificaciones
cur = conn.cursor()
cur.execute("LISTEN nuevos_productos")
print("Esperando nuevas notificaciones...")
while True:
print("Calling poll()")
state = conn.poll()
print(state)
if conn.poll():
print("aca3")
while conn.notifies:
for notify in conn.notifies:
print(f"Received notification: {notify.payload}")
oid = int(notify.payload)
# Consultar el nuevo registro en la tabla
cur.execute("SELECT * FROM productos_precios_historico WHERE oid = %s", (oid,))
producto = cur.fetchone()
if producto:
# Formatear el mensaje a enviar
mensaje = f"Nuevo producto añadido:nn"
mensaje += f"SKU: {producto[1]}n"
mensaje += f"Precio normal: {producto[2]}n"
mensaje += f"Precio internet: {producto[3]}n"
mensaje += f"Precio 4: {producto[4]}n"
# Enviar el mensaje
enviar_mensaje(mensaje)
conn.notifies.clear()
else:
print("No notifications received.")
time.sleep(1)
# Iniciar el monitoreo de la tabla
if __name__ == "__main__":
monitorear_tabla()
</code>
import telebot
import select
import psycopg2
from psycopg2 import sql
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
from datetime import datetime, timedelta
import time
PSYCOPG_DEBUG=1
# Token del bot de Telegram
TOKEN = 'ddd'
# ID del chat donde enviar los mensajes
CHAT_ID = '-1002208074761'
# Configuración de la conexión a PostgreSQL
DATABASE = "tienda"
USER = "postgres"
PASSWORD = "password"
client_encoding='utf8'
# Conexión a PostgreSQL
conn = psycopg2.connect(database="tienda", user="postgres", password="12345", client_encoding='utf8', host='localhost', port='5432',async_=False )
# Crear objeto bot
bot = telebot.TeleBot(TOKEN)
# Función para enviar mensaje a Telegram
def enviar_mensaje(texto):
bot.send_message(CHAT_ID, texto)
# Función para monitorear la tabla y enviar mensajes
def monitorear_tabla():
# Mantener la conexión abierta para recibir notificaciones
#conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
print('aca')
# Crear un objeto para escuchar notificaciones
cur = conn.cursor()
cur.execute("LISTEN nuevos_productos")
print("Esperando nuevas notificaciones...")
while True:
print("Calling poll()")
state = conn.poll()
print(state)
if conn.poll():
print("aca3")
while conn.notifies:
for notify in conn.notifies:
print(f"Received notification: {notify.payload}")
oid = int(notify.payload)
# Consultar el nuevo registro en la tabla
cur.execute("SELECT * FROM productos_precios_historico WHERE oid = %s", (oid,))
producto = cur.fetchone()
if producto:
# Formatear el mensaje a enviar
mensaje = f"Nuevo producto añadido:nn"
mensaje += f"SKU: {producto[1]}n"
mensaje += f"Precio normal: {producto[2]}n"
mensaje += f"Precio internet: {producto[3]}n"
mensaje += f"Precio 4: {producto[4]}n"
# Enviar el mensaje
enviar_mensaje(mensaje)
conn.notifies.clear()
else:
print("No notifications received.")
time.sleep(1)
# Iniciar el monitoreo de la tabla
if __name__ == "__main__":
monitorear_tabla()