Бот с базой данных Telegram python postgresql

Для многих новичков в разработке на Python возникает проблема как подключить базу данных? Я сам столкнулся с такой проблемой в начале разработки. Тема оказалось довольно простой, но в интернете есть множество гайдов, которые могут запутать. В этом туториале я расскажу о том, как просто интегрировать базу данных Sqlite3 на примере Telegram бота.

Начало работы

Для работы нам понадобятся базовые знания в Python, достаточные для написания простого бота. Данный гайд можно использовать не только для интеграции с ботом, но и для других проектов. Если вы не используете PyCharm, и у вас нет средства для работы с БД, то необходимо установить утилиту SQLiteStudio с официального сайта.

Теперь давайте перейдем к написанию кода. В терминале необходимо установить pyTelegramBotAPI (если по какой-то причине у вас его нет).

pip install pyTelegramBotAPI

Далее создаем новый файл с расширением .py. В нем прописываем следующее:

import sqlite3import telebotbot = telebot.TeleBot(«token»)

Устанавливать sqlite3 не нужно это стандартная библиотека. Вместо «token» необходимо указать токен бота, который выдал вам BotFather. Теперь проверим, работает ли бот.

#9. Работа с базой данных PostgreSQL через gino | Aiogram

Запустим код. Если при запуске бота он пишет нам «Добро пожаловать», то все работает отлично.

Как мы видим, все работает.

Настройка базы данных

Открываем SQLiteStudio. Во вкладке Database выбираем пункт Add a database. Для удобства можно использовать сочетание Ctrl+O.

Далее нажимаем на зеленую кнопку Создать новый фал базы данных. Выбираем директорию вашего проекта. В ней можете создать отдельную папку db, где будет хранится файл с базой. Вводим название, например database. Расширение будет присвоено автоматически. Нажимаем Сохранить. Теперь слева в списке у нас появился наш файл. Кликаем по нему ПКМ и выбираем пункт Connect to the database. Соединение с базой установлено. Появилось два подпункта: Таблицы и Представления. В этом уроке мы будем затрагивать только пункт Таблицы. Нажимаем по нему ПКМ и выбираем Add a table.

В поле для ввода указываем имя для таблицы. Я назову ее test. Чуть выше есть активная кнопка Добавить столбец (Ins). В появившемся окне указываем название столбца и тип данных. Для начала вам могут понадобится такие условия, как Первичный ключ, Не NULLи Уникальность. Первый столбец я назову id, выберу тип данных INTEGER и установлю все три условия. У Первичный ключ выберу настройку Автоинкремент. Этот столбец будет автоматически создавать ID записи в таблице. Работать с ним в коде мы не будем.

Второй столбец будет хранить user_id. Он будет иметь тип данных INT, уникален и не равен нулю. Третий столбец я назову user_name, присвою тип данных STRING и выберу пункт Не NULL. Еще 2 столбца будут называться user_surname и username. После того, как вы создали столбцы, нажимаем зеленую кнопку с галочкой.

В общем все будет выглядеть вот так.

Работа с базой данных в коде

Теперь давайте вновь перейдем к коду. Создадим 2 переменные.

Еще по теме:  Какое время посещения показывает Телеграмм

conn = sqlite3.connect(‘db/database.db’, check_same_thread=False)cursor = conn.cursor()

В первой мы подключаем нашу базу данных, а во второй создаем курсор для работы с таблицами. Обратите внимание на то, что у меня в директории проекта создана папка db, а уже в ней находится файл БД. Если у вас по другому, укажите расположение в первой переменной.

Теперь создадим функцию, которая будет нужна непосредственно для работы с таблицей.

def db_table_val(user_id: int, user_name: str, user_surname: str, username: str):cursor.execute(‘INSERT INTO test (user_id, user_name, user_surname, username) VALUES (?, ?, ?, ?)’, (user_id, user_name, user_surname, username))conn.commit()

Итак, сейчас объясню, что тут происходит. В аргументах функции мы указываем переменную user_id с типом данных inst. Далее добавляем запись в таблицу test в столбец user_id. С остальными значениями точно так же. В конце мы просто применяем изменения. Эта функция не будет выполнятся, пока мы ее не вызовем. Давайте исправим это. Создадим обработчик сообщений от пользователя и будем вносить в базу его данные.

В переменные мы вносим имя пользователя, id, имя и фамилию в Telegram, а потом сохраняем в БД. В конце кода можем сделать так, чтобы бот работал постоянно.

bot.polling(none_stop=True)

Пришло время проверить, как работает код. Запускаем бота и пишем ему «Привет».

Теперь можем зайти в SQLiteStudio, и выбрав вкладку Данные посмотреть что получилось:

Как мы видим, данные уже в базе. Если их по какой-то причине нет, то обновите базу, нажав на синюю кнопку Обновить

Заключение

В этой статье мы немного познакомились с sqlite3 и сделали простой скрипт добавления сведений о пользователе. Этого, конечно, не достаточно. В скором времени выпущу продолжение, в котором затрону тему удаления пользователей и редактирования полей.

Огромное спасибо за то, что прочитали. Надеюсь, кому-то помог. Всем удачи и поменьше багов в коде!

Источник: personeltest.ru

Creating a telegram bot (Spring Boot, Kafka, PostgreSQL), part one

Even a person of average ability, stubbornly studying one subject, will certainly achieve deep knowledge in it. -

Hello everyone, this article is a kind of my first, but still I will try to tell you as simply as possible about how to create a bot by screwing all the whistles promised above.

The articles will be divided into 2 parts, the first part is the creation of the main bot with sending logs (Kafka Producer) and writing them to the database, the second part is the processing of all logs (Kafka Consumer).

Ingredients:

  1. Bot registration
  2. Creating a Spring Boot project, the easiest way to do this is through the built-in configurator in IntelliJ IDEAor using Spring Initializr. (as the build system will be used gradle)
  3. Kafka (to keep track of topics I use conductor)
  4. PostgreSQL (for comfortable work I use DBeaver)

Please write in the comments if you have any problems, just in case – here’s mine git

Let’s start with cutting:

First you need to set up build.grable with all dependencies

build grable
buildscript < repositories < mavenCentral() >> plugins < id ‘org.springframework.boot’ version ‘2.4.2’ id ‘io.spring.dependency-management’ version ‘1.0.11.RELEASE’ id ‘java’ >apply from: ‘build-test.gradle’ group ‘com.sercetary.bot’ sourceCompatibility = ’14’ configurations < compileOnly < extendsFrom annotationProcessor >> repositories < mavenCentral() >configurations.all < exclude module: ‘slf4j-log4j12’ >dependencies

Next, for Kafka to work, we will describe application.yml, which contains the settings of our kafka producer

server: port: 9000 spring: kafka: producer: bootstrap-servers: localhost:9092 key-serializer: org.apache.kafka.common.serialization.StringSerializer value-serializer: org.apache.kafka.common.serialization.StringSerializer

Now application.properties settings

# HTTP port for incoming requests server.port=8081 app.http.bot=change-me telegram-bot.name=change-me telegram-bot.token=change-me # Bot db app.db.bot-db.url=jdbc:postgresql://localhost:5432/change-me app.db.bot-db.driver=org.postgresql.Driver app.db.bot-db.user=change-me app.db.bot-db.password=change-me app.db.bot-db.pool-size=10 # logging logging.level.root=INFO logging.level.org.springframework.web=DEBUG logging.level.ru.centerinform.webhook=TRACE logging.file.name=change-me

Okay, after setting up our project, let’s talk about its structure:

Project structure

  • config – description of beans and project configuration
  • controller – handles the user’s request
  • dto – stores data, and also describes the database table model
  • exceptions – custom error handler package
  • repository – logic for working with the database
  • service – the main business logic of the project
Еще по теме:  Что написать в строке о себе в Телеграмме

Now we collect the ingredients and marinate:

Bin settings:

– First of all, we write the configuration of the beans of our application in the config package, here are the TelegramBotsApi and ObjectMapper initialization settings

– Inside our DbConfig class, there is a SpringDataJdbcProperties class that describes the SpringDataJdbc settings

– Create a base class to reduce duplication of bean initialization code

– After we write a utility class for logging

Next, we will write a controller to access the service from outside

– Create a simple controller to get a list of records from the database

Then we move on to creating the model.

– We create a user model User, as well as its UserMapper, which is needed to work with the database and map fields in the table

UserMapper

Let’s move on to creating custom exceptions

What are they needed for

We use them to handle errors that may occur during the operation of the application so that the bot does not break down and continues its work.

– BaseException – a class that inherits from RuntimeException, in the constructor takes 2 parameters – the message and the body of the error

– NotFoundException – the class that is called when the answer is not found, inherited from BaseException

– DbException – a class that handles errors related to the database, inherited from RuntimeException

Now to work with the database, create a repository

– Let’s create an interface that describes methods for working with records in the database

– Now let’s write a class that implements interface methods

– Next, we have the logic of the bot, everything is trivial here, in the inherited onUpdateReceived method from the parent class TelegramLongPollingBot we write the behavior that happens when the chat with the user is updated, more about this herealso in the message processing method there is a call to our producer and writing data to the database

Code snippet with sending to Kafka and writing to the database
if (requestMessage.getText().startsWith(«/»)) < entity.setStartWord(«команда: «); producerService.sendMessage( entity); >else

Let’s move on to creating the business logic of the application

– BaseService – implements the basic methods of project services

– The UserService class works with our IUserRepository repository and contains the business logic for working with event records in the database

– The Producer class, just the class that sends messages to the users topic, and here we can change the format of the message itself and the data that it sends

At the end of the class, which actually launches our entire application

webhookapp

Now we have marinated all the ingredients and prepared the dish for baking:

– First check if Kafka is running

start by command - sudo su systemctl start kafka

– After that, we launch Conductor and see that we have a message broker running, after launching our application, a users topic will appear here, to which messages sent by our producer will fly

Launched Broker

– Next, run DBeaver and create 2 tables (log and user_table), here is the scheme for creating tables:

CREATE TABLE public.log ( id serial4 NOT NULL, message varchar(500) NOT NULL, date_time date NOT NULL, topic varchar(100) NOT NULL, CONSTRAINT log_pkey PRIMARY KEY (id) );
CREATE TABLE public.user_table ( id serial4 NOT NULL, user_name varchar(100) NOT NULL, description varchar(500) NULL, CONSTRAINT user_table_pkey PRIMARY KEY (id) );

DB schema publicThis is what the log table looks likeThis is what the user_table looks like

Great, the dish is baked and ready to serve:

– We start the project, check that everything is configured and works correctly

Spring logs

– Open telegrams and taste our “Frankenstein”

Chatting with a Telegram bot

– Let’s see what Spring wrote to us in the logs and whether the data was written to Kafka and the database?

Еще по теме:  1 аккаунт Телеграм на 2х устройствах

Logs of our bot, no errors observed

– As we can see, the messages sent to the Bot appeared in the database

Records in the database

– Having opened the conductor, go to the topics tab, then click on our users topic

topics tab

– Next, in the tab of our topic, click on the CONSUME DATA button

Topic information users

– In the window that opens, set the same settings (the most important of them is Start From – indicates from what moment to show messages in Kafka, our setting – shows all messages, including those sent earlier)

Message view settings

– That’s all, now we have made sure that the messages arrived safely in Kafka, registered in the database and did not cause errors in the application

Messages arriving in Kafka

Well, thank you all so much for taking the time to read this article, I look forward to seeing you in second part See this tutorial where we use Consumer Kafka to handle incoming messages.

Источник: prog.world

(Решено): напиши код python для анонимного чат бота Telegram с использованием mysql базы…

Искуственный интеллект во многом преуспевает, но в некоторых областях может давать неточные ответы.
Если вам не понравился ответ, попробуйте задать его более развёрнуто и конкретно, используя точные параметры.

Ответ нейросети:

Для создания анонимного чат-бота Telegram с использованием базы данных MySQL, вам нужно зарегистрировать бота через BotFather и получить токен. Затем вы должны создать базу данных MySQL или использовать уже существующую и создать таблицу для хранения сообщений.

1) Установите модуль telebot и mysql-connector-python:

pip install pyTelegramBotAPI pip install mysql-connector-python

2) Импортируйте модули и установите соединение с базой данных MySQL:

import telebot import mysql.connector mydb = mysql.connector.connect( host=»localhost», user=»username», password=»password», database=»chatbot» )

3) Создайте таблицу для хранения сообщений:

mycursor = mydb.cursor() mycursor.execute(«CREATE TABLE IF NOT EXISTS messages (id INT AUTO_INCREMENT PRIMARY KEY, user_id INT, username VARCHAR(255), message TEXT)»)

4) Инициализируйте бота и напишите функцию для обработки сообщений:

5) Запустите бота и начните переписку анонимно:

bot.polling()

Теперь вы можете запустить код для создания анонимного чат-бота Telegram с использованием базы данных MySQL. Бот будет сохранять сообщения в базу данных и отправлять их обратно пользователю.

Чтобы оставить комментарий, необходимо авторизоваться.

Задай любой вопрос нейросети!

она справится с любой поставленной задачей быстрее чем поиск в Яндекс.

Для того, чтобы задать вопрос нейросети, необходимо войти на сайт.

Последние вопросы

Последние вопросы:

(c) ChatGPT по русски 2023. Все права защищены. При обнаружении неправомерного контента пишите на [email protected]

Хотите задать любой вопрос нейросети?

Нажимая «Регистрация» или «Войти через Google», вы соглашаетесь с Публичной офертой, даете Согласие на обработку персональных данных, а также подтверждаете что вам есть 18 лет»

Форма репорта неправомерного контента.
Обратная связь с администрацией проекта

При использовании данного сайта, вы подтверждаете свое согласие на использование файлов cookie и других похожих технологий в соответствии с настоящим Уведомлением.

Если Вы не согласны, чтобы мы использовали данный тип файлов, Вы должны соответствующим образом установить настройки Вашего браузера или не использовать наш сайт.

Обращаем Ваше внимание на то, что при блокировании или удалении cookie файлов, мы не можем гарантировать корректную работу нашего сайта в Вашем браузере.

Cookie файлы, которые сохраняются через веб-сайт, не содержат сведений, на основании которых можно Вас идентифицировать.

Файл cookie представляет собой небольшой текстовый файл, сохраняемый на вашем компьютере, смартфоне или другом устройстве, которое Вы используете для посещения интернет-сайтов.

Некоторые посещаемые Вами страницы могут также собирать информацию, используя пиксельные тэги и веб-маяки, представляющие собой электронные изображения, называемые одно-пиксельными (1×1) или пустыми GIF-изображениями.

Файлы cookie могут размещаться на вашем устройстве нами («собственные» файлы cookie) или другими операторами (файлы cookie «третьих лиц»).

Рейтинг
( Пока оценок нет )
Загрузка ...