Trigger for insert into table Python Postgresql

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<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()

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật