Autonomous Business — Telegram channel + LLM

Hello everyone, in this article I would like to talk about creating a script for rewriting Telegram channel posts using the LLM model and publishing them on your channel.

The first thing we need is a locally raised LLM model to process posts – modify them.

The second is the script itself.
We import the necessary libraries:

from telethon import TelegramClient
from telethon import events, sync
import re
from bs4 import BeautifulSoup
import requests
from g4f.client import Client
from openai import OpenAI

We register the client for interaction with the Telegram API, namely receiving posts from channels. It is important to register the correct parameters, otherwise you can get a ban from Telegram for your account – it is better to use a non-main account.

clients = TelegramClient('my-client', api_id, api_hash')

Add a client to access the LLM model to convert text:

client = OpenAI(
         base_url="http://localhost:11434/v1",
         api_key='******',
        )

We add an event handler that will process posts from the channel in real time:

@clients.on(events.NewMessage(chats=channel_username))
async def handler(event):
    message = event.message.message
    matches = pattern.findall(message)
    if matches:
        for match in matches:
            print(match)

We get the last added post from the channel:

result_content_post = soup.find("meta", {"name": "twitter:description"}).attrs['content']
            print(result_content_post)

We turn to the LLM model to transform the post:

response = client.chat.completions.create(
           model="LLM",
           messages=[{"role": "user", "content": f"Сделай рерайт текста: {result_content_post}"}],
        )

For more convenient operation of the script, we run it from a docker container, below is the Dockerfile:

FROM python:3.12

ADD main.py  .
ADD my-client.session .

RUN pip install telethon bs4 requests g4f curl_cffi lxml nest-asyncio openai

CMD ["python", "-u", "./main.py"]

This option for using the LLM model in Telegram is one of many variations of its use; you can implement the LLM model to respond to new comments in business account posts.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *