An open API service indexing awesome lists of open source software.

https://github.com/serhii-chernenko/chatgpt-telegram-bot

Telegram bot based on ChatGPT API
https://github.com/serhii-chernenko/chatgpt-telegram-bot

ansible-playbook chatgpt nodejs openai telegraf telegram-bot

Last synced: 6 months ago
JSON representation

Telegram bot based on ChatGPT API

Awesome Lists containing this project

README

          

# ChatGPT
Telegram bot based on ChatGPT API

Телеграм бот на базі API від ChatGPT

Example:

Приклад:

https://t.me/ixGPTbot


## Prepare to use
Підготуй для використання

### ChatGPT

Make sure that you have a created account in OpenAI service:

Переконайся, що в тебе є зареєстрований акаунт в OpenAI сервісі:

https://openai.com/

Create a new API key there:

Створи новий API ключ:

https://platform.openai.com/account/api-keys

### Docker
Докер

There's only one thing that you need in your OS is Docker.

Єдине, що тобі потрібно встановити до ОС - це Docker.

Open the link below and follow instructions:

Відкрий посилання та слідуй інструкціям:
https://docs.docker.com/get-docker/

## How to run
Як запустити

### Clone current repo
Клонувати поточну репу

Run the command in your terminal.

Виконай команду в терміналі.

```shell
cd /path/to/directory/with/projects
git clone git@github.com:Inevix/chatgpt-telegram-bot.git
cd $_
```

### Create your own bot in Telegram
Створити власного бота в Телеграмі

Now you have to create a new bot to get an API bot token.

Зараз тобі потрібно буде створити нового бота, щоб отримати АПІ токен боту.

Open the chat:

Відкрий чат:

https://t.me/BotFather

Send the command message to the bot:

Відправ боту команду:
```shell
/newbot
```

And follow instructions

Та слідуй інструкціям.

Also, at current step I recommend you to create second bot, 'cause you will have 2 environments:

Також на цьому етапі я хотів би порадити тобі створити ще одного бота, бо в тебе буде 2 оточення:
- `dev`
- `production`

It includes different docker containers and different databases. In this case, better to have 2 different bots with different tokens to run them separately.

Я маю на увазі різні докер контейнери та бази даних. В цьому випадку краще мати 2-х різних ботів з різними токенами, щоб запускати їх окремо.

### Prepare .env file
Підготуй .env файл

In the new `chatgpt-telegram-bot` directory you can find the directory `env` with the file `.env.example`.

В новій директорії `chatgpt-telegram-bot` ти можеш знайти ще одну директорію `env` з файлом `.env.example`.

First of all copy and rename this file to 2 different files such as: `.env.dev` and `.env.production`.

Для початку, зроби 2 копії цього файлу та перейменуй його в `.env.dev` та `.env.production`.

```shell
cp env/.env.example env/.env.dev
cp env/.env.example env/.env.production
```

### Set the OpenAI token
Вказати токен OpenAI

Open both env files and set the tokens as values of the `OPENAI_API_KEY` variable.

Відкрий обидва env файли та вкажи отримані токени, як значення для змінної `OPENAI_API_KEY`.

```dotenv
OPENAI_API_KEY="xx-xxxxx..."
```

### Set the bot telegram token
Вказати токен телеграм боту

Open both env files and set the tokens as values of the `TELEGRAM_BOT_TOKEN` variable.

Відкрий обидва env файли та вкажи отримані токени, як значення для змінної `TELEGRAM_BOT_TOKEN`.

```dotenv
TELEGRAM_BOT_TOKEN="xxxxx:xxxxx..."
```

Don't forget that better to use different bots with different tokens for `dev` and `production` modes.

Не забудь, що краще використовувати різних ботів з різними токенами для `dev` та `production` режимів.

### Set allowed users
Вказати дозволених юзерів

Open both env files and set telegram usernames to the `ALLOWED_USERS` variable which allowed to use your bot.

Відкрий обидва env файли та вкажи телеграм юзернейми, яким ти хочеш дати доступ для користуванням ботом, як значення для змінної `ALLOWED_USERS`.

```dotenv
# Only one / Тільки один
ALLOWED_USERS="username"
# Some users / Для декількох юзерів
ALLOWED_USERS="username1 username2 username3..."
```

Before you'll add a lot of users, remember that you have only $18 for the trial period ~3 months.

Перед тим, як давати доступ великій кількості людей, памʼятай, що безкоштовно ти можеш використовувати чат тільки 3 місяці і маєш на це $18.

Check usage:

Перевірити використання:

https://platform.openai.com/account/usage

### Run docker containers in the developer mode
Запусти докер контейнери в режимі розробника

```shell
npm run docker:dev
```

The command `docker:dev` and other you can find in the `package.json` file.

Команду `docker:dev` та інші ти можеш знайти у файлі `package.json`.

### Run the bot in the production mode
Запусти бота в продакшн режимі

When you run the bot in the developer mode you can't run docker containers in a background, and you see a lot of logs from telegram updates. You can prevent this. Feel free to run the bot in background mode without any logs of telegram updates by the command:

Коли ти запускаєш бота в режимі розробника, ти не можеш запустити докер контейнери у фоні, а також ти бачиш багато логів після кожного оновлення в чаті з ботом. Ти можеш цьому зарадити. Запустити бота у фоні без логів можна за допомогою команди:
```shell
npm run docker:start
```

Additional commands:

Додаткові команди:
```shell
npm run docker:start
npm run docker:stop
npm run docker:restart
```

## Time to make changes
Час вносити зміни

### Editing
Редагування

Run the bot in the developer mode:

Запусти бот в режимі розробника:
```shell
npm run docker:dev
```

Next feel free to edit any files in the `bot` directory.

Далі зміни будь який файл в директорії `bot`.

### Local NPM packages
Локальні NPM пакети

Before go next steps, you have to install NPM packages to your local machine too.

Перед тим, як рухатися далі, ти маєш встановити NPM пакети локально також.

If you don't have Node.js locally, please visit the [site](https://nodejs.org/en/).

Якщо в тебе немає Node.js локально, відвідай цей [сайт](https://nodejs.org/uk/).

Next just install NPM packages to the project directory.

Далі просто встанови NPM пакети в директорію проєкту.
```shell
npm i
```

### Code inspecting
Перевірка коду

There is the `.eslintrc.js` file in the project to present rules for [ESLint](https://eslint.org/).

В проєкті є `.eslintrc.js` файл з правилами для [ESLint](https://eslint.org/).

Configure your code editor to follow rules:

Налаштуй свій редактор коду під вказані правила:
- [VSCode](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint)
- [PHPStorm](https://www.jetbrains.com/help/phpstorm/eslint.html)

### Code formatting
Форматування коду

There is the `.prettierrc.js` file in the project to preset rules for [Prettier](https://prettier.io/).

В проєкті є `.prettierrc.js` файл з правилами для [Prettier](https://prettier.io/).

Configure your code editor to follow rules:

Налаштуй свій редактор коду під вказані правила:
- [VSCode](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode)
- PHPStorm:
- [Plugin / Плагін](https://plugins.jetbrains.com/plugin/10456-prettier)
- [Configuration / Налаштування](https://www.jetbrains.com/help/phpstorm/prettier.html)

## Contributing
Долучитися до проєкту

I'm really excited if you are interested in the improving of my project. Thanks so much!

Я дійсно в захваті, що ти зацікавився покращенням мого проєкту. Дуже тобі вдячний!

There are some steps how you can do that:

Тут декілька кроків, що потрібно зробини для цього:
1. Fork my repository.
Зроби форк мого репозиторію.
2. Deploy the project locally (follow instructions above).
Розгорни проєкт локально, слідуючи інструкціям вище.
3. Make your changes.
Внеси свої зміни.
4. Make sure that your changes have been self-checked by you.
Обовʼязково перевір свої зміни власноруч.
5. Make sure that you followed rules of ESLint and Prettier. I can't merge your changes if you'll ignore this point.
Переконайся, що в тебе налаштовані ESLint та Prettier. Без них я не прийму твій код.
6. Create a new PR (Pull Request) from your repo to mine.
Зроби новий ПР (запит на внесення коду) з твоєї репи до моєї.
7. Wait while I'll check that.
Очікуй, поки я не перевірю.
8. If I don't agree with your changes, be absolutely sure that I'll write a comment why I think so.
Якщо я не згодний зі змінами, будь певний, я обовʼязково відпишу чому.
9. If I want to see your changes in the project:
Якщо мені подобаються твої зміни:
- I'll merge the PR if everything is fine.
Я внесу їх, якщо все добре.
- I'll ask you to do some fixes if something will be wrong.
Я попрошу тебе зробити певні правки, якщо щось буде не так.