Nohup python bot python

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

A telegram bot that allows you to chat with ChatGPT.

License

moerv9/chatgpt-telegram-bot

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Читайте также:  Порт сервера для css

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

A telegram bot that allows you to chat with ChatGPT.

The package to interact with ChatGPT is from here. Thanks to Antonio Cheong for the great work.

  • : Run ChatGPT in Telegram locally
  • : Let multiple people join with the same
  • : Write article on Medium
  • : Run ChatGPT in Telegram on a server

Create a Bot with Botfather and get the API key.

Add BOT_TOKEN to a file named .env in the root directory of the project.

Install Telegram Bot API. You can do this by running the following command in your terminal:

pip install pyTelegramBotAPI 

Follow Installation and Configuration steps to install ChatGPT from here

Add SESSION_TOKEN to config.json and .env-file.

run the following command in your terminal:

Using ChatGPT in Telegram

Connect to Server via ssh and copy folder to server.

Check if Python is installed (otherwise install it).

Get current path on server with pwd: /home/ubuntu/chatgpt-telegram

scp -r folder username@hostname:~/path/to/folder 

Install venv and create virtual environment:

sudo apt-get install python3-venv mkdir myenv cd myenv python3 -m venv . 

Activate virtual environment:

Check if the environment is active:

pip install -r requirements.txt > **Note** This may not work and you have to manually install the packages via `sudo apt . ` 

To run a script on a server in the background use nohup

If you want to log the output of the script into a file add this:

nohup python3 bot.py > output.log & or nohup python3 bot.py > output.log 2>%1 & 

To stop the script, use ps to get the process id and kill to stop the process.

ps -ef | grep python3 kill -9

Chrome or Chromedriver Errors

The config.json file contained a «proxy»-field and it lead to an error I couldn’t solve. I removed it and it worked. If you have the same problem, try to remove the field.

If you have some problems with selenium or chromedriver, make sure to have Chrome installed and that ChromeDriver is compatible with your Chrome version. You can check the version of Chrome with google-chrome —version and the version of ChromeDriver with chromedriver —version . They must have the same version!

You might also try to add the paths for the browser and driver into your config.json like this:

"driver_exec_path": "./path/to/driver", "browser_exec_path": "./path/to/browser", 
  • Stuck in «Browser spawned.» Installed new chromedriver and google-chrome on Server. /home/ubuntu/chatgpt-telegram-bot/venv/lib/python3.10/site-packages/revChatGPT/ChatGPT.py
  • Chromedriver Issues on Server Install the X Virtual Framebuffer display server apt install xvfb -y Set DISPLAY environmental variable to :1 export DISPLAY=:1 Start a Xvfb process in the background Xvfb $DISPLAY -screen $DISPLAY 1280x1024x16 &

About

A telegram bot that allows you to chat with ChatGPT.

Источник

Hosting a discord.py bot¶

In this section, we aim to install python3.8 to the server, note that debian users should be running these commands as root while ubuntu users can either use root or run these commands with sudo as a sudo user .

Since Debian 8 and lower don’t have the required Python version that discord.py requires. You can always use a tool like pyenv to easily compile and install any Python version that you want, however it won’t be covered in this topic.

sudo apt update sudo apt-get install software-properties-common -y sudo add-apt-repository ppa:deadsnakes/ppa -y sudo apt install python3.8 python3.8-dev python3.8-venv python3-pip -y 
echo "deb http://http.us.debian.org/debian/ testing non-free contrib main" >> /etc/apt/sources.list apt update apt install python3 -y 

Congrats! You now have Python 3.8 installed with pip. Now we can install the required dependencies for the bot to run.

Change to the path of your bot.

You should replace discord_bot with the folder you uploaded to the server

Recommended: Create a virtual enviroment and activate it.

python3.8 -m venv venv source venv/bin/activate 

A virtual environment, or most commonly referred to as a venv, is an isolated environment for projects so you don’t have to worry about polluting the global namespace. See the official documentation for more information.

You do not need to create a new one every time you start, modify or stop the bot.

Install the discord.py package.

If you use discord.py’s voice features, then i would suggest appending [voice] at the end of the command.

To install from a requirements.txt file, simply run pip install -Ur requirements.txt instead.

Running your bot¶

We installed our required dependencies and there’s only one last thing to do, run the bot.

To run your bot you would simply do

If you use a file like launcher.py to start your bot, replace bot.py with that instead.

Encountering a ModuleNotFound: No module named ‘discord’ when trying to run the command above? Chances are you didn’t activate the virtual environment or install the dependency.

Now you can close your SSH client, but chances are is that your bot will stop which can be frustrating. Luckily, you can solve this by using a process manager such as systemd or a terminal multiplexer like screen to keep the session alive when you close your SSH connection. Read further down to learn how to utilize these programs.

Systemd¶

The most common init system you’ll ever find on a Linux distro.

To create and start editing a service file called my_bot , you would do

nano /etc/systemd/system/my_bot.service 

Replace nano with the editor you choose, otherwise leave it be.

Replace my_bot with the name of your bot

We will just use this boilerplate for our bot, make sure you change this to the appropriate values.

[Unit] Description=My Python Discord Bot After=multi-user.target [Service] WorkingDirectory=/root/discord_bot # This is where your bot's code lies User=root # Change user if you aren't using root # Activates your virtual environment and starts the bot # replace bot.py with whatever Python file that starts your bot ExecStart=/bin/bash -c "source venv/bin/activate && python bot.py" # This will restart your bot if your bot doesn't return a 0 exit code Restart=on-failure [Install] WantedBy=multi-user.target 

If you don’t use virtual environments, then you can just reassign the ExecStart part to ExecStart=/usr/bin/python3.8 bot.py

To save these changes in nano you would simply type CTRL-X to save your change, y to confirm the change, and Enter to write that change to /etc/systemd/system/my_bot.service

Now you would enter this command to tell systemd to see your newly created or changed service files.

To start your bot, you would execute

To stop your bot, you would execute

To restart your bot, you would execute

To start your bot on VPS start, you would simply do

and to revoke that you would do

Screen¶

Most beginners would prefer this option as it’s pretty straightforward, but it doesn’t offer you the features a process manager would offer such as starting, stopping, and restarting your bot as systemd would.

To create a session called my_bot , you would do

Feel free to replace my_bot with something else.

You may have noticed that it cleared your screen, which is completely normal. This session will stay here forever until you explicitly close it or if the server shuts down.

In order to get your bot running, you must activate the virtual environment

Now, since you have your dependencies already installed and your virtual environment activated, you can start the bot with the following.

Replace bot.py with whatever file you use to start your bot

Now you can simply disconnect from the session with CTRL A and D or just close the connection with your server. Congrats, your bot is running on a VPS without the need to keep your computer on.

Now if you would like to re-attach to my_bot ‘s session you would simply enter

If you used a different name don’t forget to use that. screen -ls will also list all active screens.

To detach from the bot’s session without closing it you would simply hit CTRL A and D with your keyboard.

To see how many screen sessions you have, simply enter

You should see a output similar to this

[email protected]:~$ screen -ls There is a screen on: 4146.my_bot (03/30/2020 12:09:15 AM) (Detached) 1 Socket in /run/screen/S-equity. [email protected]:~$ 

The (Detached) on the far right means we aren’t in the virtual session, otherwise it would be (Attached)

Nohup¶

On many Linux systems (if not all), including Ubuntu and Debian, you can use nohup to run your bot even after you have closed a session. To run nohup on your discord bot, you can do this, where bot.py is the name of your bot startup file.

This will create a file in your current directory called ‘nohup.out’. You can redirect it to a file such as ‘logs.txt’ by running this instead:

nohup python3.8 bot.py &> logs.txt & 

Tada! Your bot is online, and you can close the session without the bot dying.

If you want to turn off the bot, things get a bit more complicated. You need to either get the PID of the bot’s process, then kill it, or make a command in the bot for owners that calls os._exit(1) . In this section, we’ll cover getting the PID of the bot’s process. To get the PID of the bot, you can run this:

This will display a large list of running processes. You’ll need to find the line that has «python3 bot.py» in the rightmost column, then find the PID of that line (it’s in the second column). Once you have that PID, you can run kill , and the bot will gracefully free used memory, and shut off. Now, you can run the bot again 🙂

Resources¶

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Инфа про то, как задеплоить бота на питоне на сервер LXD SSH VPS Server

gitalexhubuser/DeployBotsWinSCP

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

VPS

Недавно в телеграм чате посвященному LXD VPS хостингу — проходил конкурс на написание лучшего ( понятного ) гайда по деплою Telegram ботов на этот самый хостинг!

Деплой (deploy) — это запуск вашего веб-приложения, сайта или телеграмм бота, на удалённом сервере или хостинге.

На данный момент — конкурс уже завершен!

В данном репозитории — собраны работы всех участников.

На мой скромный взгляд — лучшим гайдом для новичка является GUIDE 1.1 — ‘nohup’ (easy guide) @gitalexhubuser

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

Если вы готовы пойти дальше, и вам нужен такой бот, которому не страшны падения и перезагрузки — то лучше изучить, как это делается при помощи другой технологии:

о которой более подробно рассказано в этих гайдах:

Guide-List

Вы так же можете написать свой гайд — отправить его мне — и я его добавлю в общий список!

About

Инфа про то, как задеплоить бота на питоне на сервер LXD SSH VPS Server

Источник

Оцените статью