Crea un Bot en Telegram para descargar archivos a tu Pi con solo poner Link o Archivo de Telegram

Sección Unicamente para Tutoriales y Guías
Avatar de Usuario
PedroRms
Pi Newbie
Pi Newbie
Mensajes: 9
Registrado: 17 Jun 2016, 18:55
Agradecido: 0
Agradecimiento recibido: 0

wat3r escribió:Bueno para hacer arrancar el programa o el Bot en el inicio de la Raspberry y suponiendo que el archivo bot.py está alojado en /home/pi, debemos crear un script con el comando.

Código: Seleccionar todo

sudo nano /etc/init.d/telegram_bot
En el debemos escribir:
#! /bin/sh
# /etc/init.d/telegram_bot

### BEGIN INIT INFO
# Provides: telegram_bot
# Required-Start: $all
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Arranque automático del Bot de telegram
# Description: Script para arrancar el bot
### END INIT INFO


# Dependiendo de los parámetros que se le pasen al programa se usa una opción u otra
case "$1" in
start)
echo "Arrancando el Bot"
# Aquí hay que poner el programa que quieras arrancar automáticamente
/usr/bin/python /home/pi/bot.py
;;
stop)
echo "Parando el Bot"
killall python
;;
*)
echo "Modo de uso: /etc/init.d/telegram_bot {start & | stop}"
exit 1
;;
esac

exit 0
Luego le damos permisos

Código: Seleccionar todo

sudo chmod 755 /etc/init.d/telegram_bot
Probamos si funciona

Código: Seleccionar todo

sudo /etc/init.d/telegram_bot start
Y para terminar habilitamos el arranque automático

Código: Seleccionar todo

sudo update-rc.d telegram_bot defaults
Saludos

Tengo instalado el bot, pero intentando activar el arranque automático con el sistema, hago la prueba con

Código: Seleccionar todo

sudo /etc/init.d/telegram_bot start
y no me encuentra el bot de telegram en la ruta especificada.

Tengo el bot instalado en un pen de 32gb en formato ext4, montado en una ruta y tal con el inicio del sistema.
En el archivo sudo nano /etc/init.d/telegram_bot he probado poniendo las rutas "/media/Sandisk/DescargasTG/bot.py" y "/dev/sda1/media/Sandisk/DescargasTG/bot.py" pero en ninguna de las dos la encuentra, no funciona :?:

Qué hago mal? Es la ruta? O por qué no me encuentra el bot?

Saludos
Avatar de Usuario
xxmonti
Pi Master
Pi Master
Mensajes: 257
Registrado: 19 May 2016, 10:05
Agradecido: 0
Agradecimiento recibido: 0

PedroRms escribió:
wat3r escribió:Bueno para hacer arrancar el programa o el Bot en el inicio de la Raspberry y suponiendo que el archivo bot.py está alojado en /home/pi, debemos crear un script con el comando.

Código: Seleccionar todo

sudo nano /etc/init.d/telegram_bot
En el debemos escribir:
#! /bin/sh
# /etc/init.d/telegram_bot

### BEGIN INIT INFO
# Provides: telegram_bot
# Required-Start: $all
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Arranque automático del Bot de telegram
# Description: Script para arrancar el bot
### END INIT INFO


# Dependiendo de los parámetros que se le pasen al programa se usa una opción u otra
case "$1" in
start)
echo "Arrancando el Bot"
# Aquí hay que poner el programa que quieras arrancar automáticamente
/usr/bin/python /home/pi/bot.py
;;
stop)
echo "Parando el Bot"
killall python
;;
*)
echo "Modo de uso: /etc/init.d/telegram_bot {start & | stop}"
exit 1
;;
esac

exit 0
Luego le damos permisos

Código: Seleccionar todo

sudo chmod 755 /etc/init.d/telegram_bot
Probamos si funciona

Código: Seleccionar todo

sudo /etc/init.d/telegram_bot start
Y para terminar habilitamos el arranque automático

Código: Seleccionar todo

sudo update-rc.d telegram_bot defaults
Saludos

Tengo instalado el bot, pero intentando activar el arranque automático con el sistema, hago la prueba con

Código: Seleccionar todo

sudo /etc/init.d/telegram_bot start
y no me encuentra el bot de telegram en la ruta especificada.

Tengo el bot instalado en un pen de 32gb en formato ext4, montado en una ruta y tal con el inicio del sistema.
En el archivo sudo nano /etc/init.d/telegram_bot he probado poniendo las rutas "/media/Sandisk/DescargasTG/bot.py" y "/dev/sda1/media/Sandisk/DescargasTG/bot.py" pero en ninguna de las dos la encuentra, no funciona :?:

Qué hago mal? Es la ruta? O por qué no me encuentra el bot?

Saludos
Pasanos el error que te da y lo vemos
Imagen
Avatar de Usuario
PedroRms
Pi Newbie
Pi Newbie
Mensajes: 9
Registrado: 17 Jun 2016, 18:55
Agradecido: 0
Agradecimiento recibido: 0

Este es el error que me aparece:

Código: Seleccionar todo

root@mediacenter-v6:~ # /etc/init.d/telegram_bot start
Arrancando el Bot
/media/Sandisk/DescargasTG/bot.py: 1: /media/Sandisk/DescargasTG/bot.py: import: not found
/media/Sandisk/DescargasTG/bot.py: 2: /media/Sandisk/DescargasTG/bot.py: import: not found
/media/Sandisk/DescargasTG/bot.py: 3: /media/Sandisk/DescargasTG/bot.py: import: not found
/media/Sandisk/DescargasTG/bot.py: 6: /media/Sandisk/DescargasTG/bot.py: API_TOKEN: not found
/media/Sandisk/DescargasTG/bot.py: 8: /media/Sandisk/DescargasTG/bot.py: Syntax error: "(" unexpected
y este es el archivo /etc/init.d/telegram_bot como lo tengo:

Código: Seleccionar todo

# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Arranque automático del Bot de telegram
# Description: Script para arrancar el bot
### END INIT INFO


# Dependiendo de los parámetros que se le pasen al programa se usa una opción u otra
case "$1" in
start)
echo "Arrancando el Bot"
# Aquí hay que poner el programa que quieras arrancar automáticamente
/media/Sandisk/DescargasTG/bot.py
;;
stop)
echo "Parando el Bot"
killall python
;;
*)
echo "Modo de uso: /etc/init.d/telegram_bot {start & | stop}"
exit 1
;;
esac

exit 0
La ruta la he copiado del file manager para que no estuviera mal escrita xD
Avatar de Usuario
xxmonti
Pi Master
Pi Master
Mensajes: 257
Registrado: 19 May 2016, 10:05
Agradecido: 0
Agradecimiento recibido: 0

Parece 1 error del bot.py de la sintaxis.
Abrelo y repasalo, hay un ) por ahí que te falta o te sobra
El API TOKEN tb esta dando fallos y la parte de Import tambien
No hagas Copy Paste, escribelo a mano porque hay guiones - que se copian mal

La parte del init.d ya se verá cuando soluciones lo de arriba

Enviado desde mi Xperia SP mediante Tapatalk
Imagen
Avatar de Usuario
PedroRms
Pi Newbie
Pi Newbie
Mensajes: 9
Registrado: 17 Jun 2016, 18:55
Agradecido: 0
Agradecimiento recibido: 0

Seguro? Si inicio manualmente el bot.py si que funciona y descargo cosas.. no quiero tocarlo y fastidiarlo..xD
Porque te refieres a editar el bot.py no? De ahi solamente modifique el id del token
Avatar de Usuario
xxmonti
Pi Master
Pi Master
Mensajes: 257
Registrado: 19 May 2016, 10:05
Agradecido: 0
Agradecimiento recibido: 0

PedroRms escribió:Seguro? Si inicio manualmente el bot.py si que funciona y descargo cosas.. no quiero tocarlo y fastidiarlo..xD
Porque te refieres a editar el bot.py no? De ahi solamente modifique el id del token
Si te funciona manualmente entonces no modifiques nada.

Comprueba que la ruta de descarga tenga todos los permisos para el usuario que estas usando
Imagen
Avatar de Usuario
xxmonti
Pi Master
Pi Master
Mensajes: 257
Registrado: 19 May 2016, 10:05
Agradecido: 0
Agradecimiento recibido: 0

Bueno, dicho esto, procedemos a instalar la API con estos tres comandos en el Terminal SSH:
CÓDIGO: SELECCIONAR TODO
git clone https://github.com/pwrtelegram/pyTelegramBotAPI
@Kike creo que este repositorio esta mas actualizado y no da tantos fallos de python:

Código: Seleccionar todo

git clone https://github.com/eternnoir/pyTelegramBotAPI.git
Imagen
Avatar de Usuario
r.garciag
Pi Newbie
Pi Newbie
Mensajes: 1
Registrado: 13 Nov 2016, 13:10
Agradecido: 0
Agradecimiento recibido: 0

Buenas, mil gracias por el tutorial, una cosilla:
He estado indagando en el bot.py pero no tengo ni idea de como añadir acceso a otro usuario más (osea, que un usuario más que yo diga, pueda usar el bot), algún alma caritativa que me ayude? jajaja :cry:
centenaro
Pi Alpha
Pi Alpha
Mensajes: 19
Registrado: 14 Ene 2017, 16:21
Agradecido: 0
Agradecimiento recibido: 0

nao intendi nada mais ainda aprendo o idioma espanhol pra ficar craque
centenaro
Pi Alpha
Pi Alpha
Mensajes: 19
Registrado: 14 Ene 2017, 16:21
Agradecido: 0
Agradecimiento recibido: 0

nao intendi nada mais ainda aprendo o idioma espanhol pra ficar craque
Avatar de Usuario
cpa
Pi Beta
Pi Beta
Mensajes: 159
Registrado: 10 Mar 2017, 23:18
Agradecido: 0
Agradecimiento recibido: 1 vez

wat3r escribió:Bueno para hacer arrancar el programa o el Bot en el inicio de la Raspberry y suponiendo que el archivo bot.py está alojado en /home/pi, debemos crear un script con el comando.

Código: Seleccionar todo

sudo nano /etc/init.d/telegram_bot
En el debemos escribir:
#! /bin/sh
# /etc/init.d/telegram_bot

### BEGIN INIT INFO
# Provides: telegram_bot
# Required-Start: $all
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Arranque automático del Bot de telegram
# Description: Script para arrancar el bot
### END INIT INFO


# Dependiendo de los parámetros que se le pasen al programa se usa una opción u otra
case "$1" in
start)
echo "Arrancando el Bot"
# Aquí hay que poner el programa que quieras arrancar automáticamente
/usr/bin/python /home/pi/bot.py
;;
stop)
echo "Parando el Bot"
killall python
;;
*)
echo "Modo de uso: /etc/init.d/telegram_bot {start & | stop}"
exit 1
;;
esac

exit 0
Luego le damos permisos

Código: Seleccionar todo

sudo chmod 755 /etc/init.d/telegram_bot
Probamos si funciona

Código: Seleccionar todo

sudo /etc/init.d/telegram_bot start
Y para terminar habilitamos el arranque automático

Código: Seleccionar todo

sudo update-rc.d telegram_bot defaults
Saludos
Me váis a perdonar que levante este hilo, pero es que he creído importante aclarar un par de cosas de este script de inicio.

1º) Si añadimos este servicio al arranque de inicio, el bot se ejecutará con permisos de root, y esto no suele ser aconsejable
2º) Tal y como hace el parado del servicio (matando todas las instancias de python), no sólo pararemos el bot, sino todos los demás programas que tengamos corriendo en python. Creo que no es la mejor opción de matar el proceso.

Respecto al error del compañero de arriba, es porque está intentando ejecutar el bot .py directamente sin pasar por python. Se ha comido el /usr/bin/python (o python2 si fuera necesario).

Mucho mejor y más currado este otro script:
https://www.domoticz.com/wiki/Installin ... legram-cli

Saludos
Avatar de Usuario
cpa
Pi Beta
Pi Beta
Mensajes: 159
Registrado: 10 Mar 2017, 23:18
Agradecido: 0
Agradecimiento recibido: 1 vez

Para contribuir de forma un poco más clara, pego aquí mi script de mi demonio para Telegram...

Este es el contenido del fichero /etc/init.d/telegram_bot

Código: Seleccionar todo

#!/bin/sh
# kFreeBSD do not accept scripts as interpreters, using #!/bin/sh and sourcing.
if [ true != "$INIT_D_SCRIPT_SOURCED" ] ; then
    set "$0" "$@"; INIT_D_SCRIPT_SOURCED=true . /lib/init/init-d-script
fi
### BEGIN INIT INFO
# Provides:          skeleton
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Example initscript
# Description:       This file should be used to construct scripts to be
#                    placed in /etc/init.d.  This example start a
#                    single forking daemon capable of writing a pid
#                    file.  To get other behavoirs, implemend
#                    do_start(), do_stop() or other functions to
#                    override the defaults in /lib/init/init-d-script.
### END INIT INFO

# Author: CpA (ForoRaspberry.es)

DIR=/home/pi/bot_Telegram
DAEMON=$DIR/bot_telegram.py
DAEMON_NAME=telegram_bot

# This next line determines what user the script runs as.
# Root generally not recommended but necessary if you are using the
# Raspberry Pi GPIO from Python.
DAEMON_USER=pi

# The process ID of the script when it runs is stored here:
PIDFILE=/var/run/$DAEMON_NAME.pid


do_start () {
    log_daemon_msg "Starting system $DAEMON_NAME daemon"
    start-stop-daemon --start --background --pidfile $PIDFILE --make-pidfile --user $DAEMON_USER --chuid $DAEMON_USER --startas $DAEMON
    log_end_msg $?
}
do_stop () {
    log_daemon_msg "Stopping system $DAEMON_NAME daemon"
    start-stop-daemon --stop --pidfile $PIDFILE --retry 10
    log_end_msg $?
}

case "$1" in

    start|stop)
        do_${1}
        ;;

    restart|reload|force-reload)
        do_stop
        do_start
        ;;

    status)
        status_of_proc "$DAEMON_NAME" "$DAEMON" && exit 0 || exit $?
        ;;

    *)
        echo "Usage: /etc/init.d/$DAEMON_NAME {start|stop|restart|status}"
        exit 1
        ;;

esac
exit 0

Recordad que debéis tener la siguiente línea en el .py para que cargue correctamente el entorno, si no, os dará errores en la importación de librerías...

Código: Seleccionar todo

#!/usr/bin/python2
En mi caso es python2, si usáis otra versión, adecuadla a la vuestra...

Espero que os sea útil...
Avatar de Usuario
xxmonti
Pi Master
Pi Master
Mensajes: 257
Registrado: 19 May 2016, 10:05
Agradecido: 0
Agradecimiento recibido: 0

Muchas gracias por la aclaracion, tendre que actualizar mi bot :victoria
Imagen
Macoy
Pi Omega
Pi Omega
Mensajes: 53
Registrado: 20 Abr 2017, 01:10
Agradecido: 0
Agradecimiento recibido: 0

Este es muy muy bueno :helado f
yoshito
Pi Alpha
Pi Alpha
Mensajes: 11
Registrado: 17 May 2016, 12:54
Agradecido: 0
Agradecimiento recibido: 0

Buenas tios

¿os rula?

Yo intento descargar cualquier fichero y siempre me el siguiente error.

2017-06-01 12:30:37,629 (__init__.py:220 MainThread) ERROR - TeleBot: "A request to the Telegram API was unsuccessful. Error code: 400 Description: SQLSTATE[HY000] [2002] Connection refused on line 21 of API.php"

No tengo ni idea de porque, si que es cierto que yo hice prueba antes con otra api de telegram (la oficial) pero lo quite todo. A ver si podeis hecharme un cable que estoy un pelin desesperado. :cry:

Saludetes y mil gracias!!!
yoshito
Pi Alpha
Pi Alpha
Mensajes: 11
Registrado: 17 May 2016, 12:54
Agradecido: 0
Agradecimiento recibido: 0

Me actualizo a mi mismo, ahora me dice esto...
2:24:15,875 (__init__.py:220 MainThread) ERROR - TeleBot: "A request to the Telegram API was unsuccessful. Error code: 400 Description: Set a custom backend to use the PWRTelegram API. Instructions available @ https://pwrtelegram.xyz"
erbeni
Pi Alpha
Pi Alpha
Mensajes: 18
Registrado: 25 Jun 2017, 15:58
Agradecido: 0
Agradecimiento recibido: 0

a mi tampoco me va,mi error es el siguiente:
Arrancando el Bot
2017-07-19 23:06:51,610 (__init__.py:220 MainThread) ERROR - TeleBot: "A request to the Telegram API was unsuccessful. The server returned HTTP 400 Bad Request. Response body:
[{"ok":false,"error_code":400,"description":"Set a custom backend to use the PWRTelegram API. Instructions available @ https:\/\/pwrtelegram.xyz"}]"
Exception in thread WorkerThread2 (most likely raised during interpreter shutdown):Exception in thread WorkerThread1 (most likely raised during interpreter shutdown):

Alguna idea?
Un saludo.
JAMON24
Pi Newbie
Pi Newbie
Mensajes: 1
Registrado: 02 Dic 2017, 19:20
Agradecido: 0
Agradecimiento recibido: 0

Con este bot se podria coger un archivo por ejemplo de un canal de peliculas y reenviarselo sin descargarlo en el movil para que se lo baje la raspberry o ya no es posible??
virapa
Pi Newbie
Pi Newbie
Mensajes: 1
Registrado: 01 Ago 2017, 00:08
Agradecido: 0
Agradecimiento recibido: 0

Hola,
Acabo de seguir los pasos del tuto y tampoco me funciona. El error es el siguiente:

Código: Seleccionar todo

2017-12-22 13:59:43,885 (__init__.py:220 MainThread) ERROR - TeleBot: "A request to the Telegram API was unsuccessful. Error code: 400 Description: Please stop using PWRTelegram.

You may have noticed that PWRTelegram is having frequent and long periods of downtime lately.
That is due to the extremely heavy load it is under currently, so please stop using it.

PWRTelegram is just an HTTP wrapper for a free and open source telegram client library called MadelineProto (https://madelineproto.xyz).
You should all use directly MadelineProto, because it is SO much faster than PWRTelegram.

It can be used from PHP and Lua (a tg-cli wrapper is also available @ https://github.com/giuseppeM99/madeline_lua_shim), and you can easily write your own HTTP wrapper using PWRTelegram (github.com/pwrtelegram/pwrtelegram) as base.

It will be available in python in December, but PLEASE use the PHP version in the meantime, it is much faster than the python version, and much easier to use.

See docs.madelineproto.xyz for the method list and full instructions (you can also make telegram voice calls with MadelineProto!).

Thanks for having used this service."
Hay version nueva basada en madelineproto.xyz?

Gracias
Un saludo.
ManuTdi
Pi Alpha
Pi Alpha
Mensajes: 27
Registrado: 07 Mar 2017, 07:33
Agradecido: 0
Agradecimiento recibido: 0

Este tutorial aún funciona bien?
Responder