20 Commits
v0.1.5 ... dev

Author SHA1 Message Date
drymer
6363684af4 Merge branch 'dev' of zlaxy/jabbergram into dev 2018-02-24 17:06:44 +00:00
523a000e01 fixed 'Message' object has no attribute 'new_chat_members' 2018-02-11 11:29:00 +03:00
drymer
42ec1749ce Fix missing parameter on docs 2017-09-01 06:20:47 +02:00
drymer
220cc1e26e Bump version 2017-07-21 08:56:44 +02:00
drymer
2679ad6f2e Adapt to telegram-bot api's change 2017-07-18 22:38:36 +02:00
drymer
002df9336e Adapt to changes in telegram's api 2017-07-09 03:07:57 +02:00
drymer
fe1cc0eed9 Fix typo 2017-07-09 03:04:15 +02:00
drymer
fca55ee84b Add docstrings 2017-07-08 21:46:10 +02:00
drymer
7f2c2513cf Rearrange imports to adapt it to pep8 2017-07-08 21:45:07 +02:00
drymer
1453f3955f Change repository's url 2017-07-08 19:51:07 +02:00
drymer
c5505f8eef Upload stickers with http upload
And fix minor things
2017-04-30 22:12:40 +02:00
drymer
ed6d8a142e Make it clearer 2017-04-30 21:42:17 +02:00
drymer
cdb54ef612 Fix typo 2017-04-30 21:41:11 +02:00
drymer
9e4e5d3852 Fix the "answer" option and some minor things 2017-02-22 17:12:11 +00:00
drymer
d926f974b7 Add name when replying 2017-01-29 02:47:46 +00:00
drymer
fa9c44b45c Add commands and support using name on telegram group name 2017-01-27 10:04:36 +00:00
drymer
b69960de08 Add http support 2016-10-13 22:11:57 +02:00
drymer
0a348f05a5 Fix typo 2016-09-26 14:21:28 +02:00
drymer
ab32df76ee Add http upload support 2016-09-26 13:19:46 +02:00
drymer
8d09508463 Minor fix 2016-09-23 21:38:55 +02:00
7 changed files with 527 additions and 212 deletions

View File

@@ -36,6 +36,8 @@
With this program, it's possible to use a MuC `XMPP` room to talk to a group on `Telegram` and vice versa. The aim of this program is to be just a simple gateway, just pass text from one way to the other. Once it's stable, it probably won't have more improvements, since I don't need them. With this program, it's possible to use a MuC `XMPP` room to talk to a group on `Telegram` and vice versa. The aim of this program is to be just a simple gateway, just pass text from one way to the other. Once it's stable, it probably won't have more improvements, since I don't need them.
Since version 0.1.6, Jabbergram has HTTP Upload support. If the server supports it, it will automatically upload all the files sent to the Telegram group.
### Installation<a id="orgheadline2"></a> ### Installation<a id="orgheadline2"></a>
As with any program that uses python, it should be used a virtual environment (virtualenv), but that is user selectable. It's possible to use one of the next installation methods: As with any program that uses python, it should be used a virtual environment (virtualenv), but that is user selectable. It's possible to use one of the next installation methods:
@@ -46,7 +48,7 @@ Install via pip:
Clone the repository: Clone the repository:
$ git clone git://daemons.cf/jabbergram $ git clone https://git.daemons.it/drymer/jabbergram
$ cd jabbergram $ cd jabbergram
$ su -c "pip3 install -r requirements.txt" $ su -c "pip3 install -r requirements.txt"
$ su -c "python3 setup.py install" $ su -c "python3 setup.py install"
@@ -74,6 +76,7 @@ Then, you will have to create a config file. We'll call it `config.ini`. In that
nick = jabbergram nick = jabbergram
token = jabbergramBotTokken token = jabbergramBotTokken
group = -10293943920 group = -10293943920
verify_ssl = yes
The only thing worth mentioning is the `token` section, which is said to you when creating the bot, and the `group`, that is the `Telegram` group ID. The only thing worth mentioning is the `token` section, which is said to you when creating the bot, and the `group`, that is the `Telegram` group ID.
@@ -90,6 +93,7 @@ There only can be one configuration file. This is because it can only be one bot
nick = jabbergram nick = jabbergram
token = jabbergramBotTokken token = jabbergramBotTokken
group = -10293943920 120301203 group = -10293943920 120301203
verify_ssl = yes
Thus, the example's muc "exampleMuc@muc.nope.org" syncs with the group "-10293943920" and "segunda@muc.sip.org" with "120 301203". Thus, the example's muc "exampleMuc@muc.nope.org" syncs with the group "-10293943920" and "segunda@muc.sip.org" with "120 301203".
@@ -114,6 +118,8 @@ Thus, the example's muc "exampleMuc@muc.nope.org" syncs with the group "-1029394
Con este programa es posible utilizar una sala `XMPP` para hablar con un grupo de `Telegram` y viceversa. El objetivo de este programa es el de ser sólo una pasarela sencilla, sólo tiene que pasar el texto de un lado al otro. Una vez que sea estable, probablemente no tendrá más mejoras, ya que yo no las necesito. Con este programa es posible utilizar una sala `XMPP` para hablar con un grupo de `Telegram` y viceversa. El objetivo de este programa es el de ser sólo una pasarela sencilla, sólo tiene que pasar el texto de un lado al otro. Una vez que sea estable, probablemente no tendrá más mejoras, ya que yo no las necesito.
Desde la versión 0.1.6, Jabbergram tiene soporte HTTP Upload. Si el servidor lo soporta, subirá automáticamente todos los archivos enviados desde el grupo de Telegram.
### Instalación<a id="orgheadline8"></a> ### Instalación<a id="orgheadline8"></a>
Como con cualquier programa escrito en `Python`, deberia ser usado en un entorno virtual (virtualenv), pero eso queda a la elección del usuario. Es posible utilizar uno de los siguientes métodos de instalación: Como con cualquier programa escrito en `Python`, deberia ser usado en un entorno virtual (virtualenv), pero eso queda a la elección del usuario. Es posible utilizar uno de los siguientes métodos de instalación:
@@ -124,10 +130,10 @@ Instalar a través de `pip`:
Clonar el repositorio: Clonar el repositorio:
$ git clone git://daemons.cf/jabbergram $ git clone https://git.daemons.it/drymer/jabbergram
$ cd jabbergram $ cd jabbergram
$ su -c "pip3 instalar requirements.txt -r" $ su -c "pip3 install -r requirements.txt"
$ su -c "python3 setup.py instalar" $ su -c "python3 setup.py install"
### Configuración<a id="orgheadline9"></a> ### Configuración<a id="orgheadline9"></a>
@@ -141,7 +147,7 @@ Este programa es simple, no tiene ni un menú de `ayuda`. Lo primero que hay que
NombreDelBot NombreDelBot
# Ahora hay que pulsar desactivar # Ahora hay que pulsar desactivar
La opción `/setprivacy` es para hacer que el robot pueda leer todo lo que se dice en el grupo, no sólo cuando se utilizan los comandos. Es necesario para hacer que `jabbergram` funcione. Más información sobre la creación los bots de `Telegrama` en su [página web](https://core.telegram.org/bots). La opción `/setprivacy` es para hacer que el robot pueda leer todo lo que se dice en el grupo, no sólo cuando se utilizan los comandos. Es necesario para hacer que `jabbergram` funcione. Más información sobre la creación los bots de `Telegram` en su [página web](https://core.telegram.org/bots).
A continuación, hay que crear un archivo de configuración, que llamaremos `config.ini`. En ese archivo, introduce los siguientes parámetros: A continuación, hay que crear un archivo de configuración, que llamaremos `config.ini`. En ese archivo, introduce los siguientes parámetros:
@@ -152,6 +158,7 @@ A continuación, hay que crear un archivo de configuración, que llamaremos `con
nick = jabbergram nick = jabbergram
token = jabbergramBotTokken token = jabbergramBotTokken
group = -10,293,943,920 group = -10,293,943,920
verify_ssl = yes
La única cosa que vale la pena mencionar es la sección del `token` (que es la que nos da cuando se crea el robot) y el `group`, que es ID del grupo de `Telegram`. La única cosa que vale la pena mencionar es la sección del `token` (que es la que nos da cuando se crea el robot) y el `group`, que es ID del grupo de `Telegram`.
@@ -168,8 +175,9 @@ Sólo puede haber un archivo de configuración. Esto es debido a que sólo puede
nick = jabbergram nick = jabbergram
token = jabbergramBotTokken token = jabbergramBotTokken
group = -10293943920 120301203 group = -10293943920 120301203
verify_ssl = yes
De este modo, el muc "exampleMuc@muc.nope.org" se sincronizará con el grupo "-10293943920", y "segunda@muc.sip.org" con "120301203". De este modo, el muc "exampleMuc@muc.nope.org" se sincronizará con el grupo "-10293943920", y "segunda@muc.sip.org" con "120301203". Hecho esto, solo queda ejecutarlo en la terminal: `python3 jabbergram.py config.ini`. Hay que tenerla activa siempre que se quiera que funcione, obviamente.
### Licencia<a id="orgheadline11"></a> ### Licencia<a id="orgheadline11"></a>

View File

@@ -2,6 +2,8 @@
** English ** English
*** About *** About
With this program, it's possible to use a MuC =XMPP= room to talk to a group on =Telegram= and vice versa. The aim of this program is to be just a simple gateway, just pass text from one way to the other. Once it's stable, it probably won't have more improvements, since I don't need them. With this program, it's possible to use a MuC =XMPP= room to talk to a group on =Telegram= and vice versa. The aim of this program is to be just a simple gateway, just pass text from one way to the other. Once it's stable, it probably won't have more improvements, since I don't need them.
Since version 0.1.6, Jabbergram has HTTP Upload support. If the server supports it, it will automatically upload all the files sent to the Telegram group.
*** Installation *** Installation
As with any program that uses python, it should be used a virtual environment (virtualenv), but that is user selectable. It's possible to use one of the next installation methods: As with any program that uses python, it should be used a virtual environment (virtualenv), but that is user selectable. It's possible to use one of the next installation methods:
@@ -12,7 +14,7 @@
Clone the repository: Clone the repository:
#+BEGIN_SRC sh #+BEGIN_SRC sh
$ git clone git://daemons.cf/jabbergram $ git clone https://git.daemons.it/drymer/jabbergram
$ cd jabbergram $ cd jabbergram
$ su -c "pip3 install -r requirements.txt" $ su -c "pip3 install -r requirements.txt"
$ su -c "python3 setup.py install" $ su -c "python3 setup.py install"
@@ -42,6 +44,7 @@
nick = jabbergram nick = jabbergram
token = jabbergramBotTokken token = jabbergramBotTokken
group = -10293943920 group = -10293943920
verify_ssl = yes
#+END_SRC #+END_SRC
The only thing worth mentioning is the =token= section, which is said to you when creating the bot, and the =group=, that is the =Telegram= group ID. The only thing worth mentioning is the =token= section, which is said to you when creating the bot, and the =group=, that is the =Telegram= group ID.
@@ -58,6 +61,7 @@
nick = jabbergram nick = jabbergram
token = jabbergramBotTokken token = jabbergramBotTokken
group = -10293943920 120301203 group = -10293943920 120301203
verify_ssl = yes
#+END_SRC #+END_SRC
Thus, the example's muc "exampleMuc@muc.nope.org" syncs with the group "-10293943920" and "segunda@muc.sip.org" with "120 301203". Thus, the example's muc "exampleMuc@muc.nope.org" syncs with the group "-10293943920" and "segunda@muc.sip.org" with "120 301203".
@@ -79,6 +83,8 @@
** Castellano ** Castellano
*** Acerca de *** Acerca de
Con este programa es posible utilizar una sala =XMPP= para hablar con un grupo de =Telegram= y viceversa. El objetivo de este programa es el de ser sólo una pasarela sencilla, sólo tiene que pasar el texto de un lado al otro. Una vez que sea estable, probablemente no tendrá más mejoras, ya que yo no las necesito. Con este programa es posible utilizar una sala =XMPP= para hablar con un grupo de =Telegram= y viceversa. El objetivo de este programa es el de ser sólo una pasarela sencilla, sólo tiene que pasar el texto de un lado al otro. Una vez que sea estable, probablemente no tendrá más mejoras, ya que yo no las necesito.
Desde la versión 0.1.6, Jabbergram tiene soporte HTTP Upload. Si el servidor lo soporta, subirá automáticamente todos los archivos enviados desde el grupo de Telegram.
*** Instalación *** Instalación
Como con cualquier programa escrito en =Python=, deberia ser usado en un entorno virtual (virtualenv), pero eso queda a la elección del usuario. Es posible utilizar uno de los siguientes métodos de instalación: Como con cualquier programa escrito en =Python=, deberia ser usado en un entorno virtual (virtualenv), pero eso queda a la elección del usuario. Es posible utilizar uno de los siguientes métodos de instalación:
@@ -89,10 +95,10 @@
Clonar el repositorio: Clonar el repositorio:
#+BEGIN_SRC sh #+BEGIN_SRC sh
$ git clone git://daemons.cf/jabbergram $ git clone https://git.daemons.it/drymer/jabbergram
$ cd jabbergram $ cd jabbergram
$ su -c "pip3 instalar requirements.txt -r" $ su -c "pip3 install -r requirements.txt"
$ su -c "python3 setup.py instalar" $ su -c "python3 setup.py install"
#+END_SRC #+END_SRC
*** Configuración *** Configuración
Este programa es simple, no tiene ni un menú de =ayuda=. Lo primero que hay que hacer es crear el bot de =Telegram=. Para ello, hay que tener una cuenta de =Telegram= y hablar con [[https://telegram.me/botfather][BotFather]]. A continuación, ejecuta: Este programa es simple, no tiene ni un menú de =ayuda=. Lo primero que hay que hacer es crear el bot de =Telegram=. Para ello, hay que tener una cuenta de =Telegram= y hablar con [[https://telegram.me/botfather][BotFather]]. A continuación, ejecuta:
@@ -107,7 +113,7 @@
# Ahora hay que pulsar desactivar # Ahora hay que pulsar desactivar
#+END_SRC #+END_SRC
La opción =/setprivacy= es para hacer que el robot pueda leer todo lo que se dice en el grupo, no sólo cuando se utilizan los comandos. Es necesario para hacer que =jabbergram= funcione. Más información sobre la creación los bots de =Telegrama= en su [[https://core.telegram.org/bots][página web]]. La opción =/setprivacy= es para hacer que el robot pueda leer todo lo que se dice en el grupo, no sólo cuando se utilizan los comandos. Es necesario para hacer que =jabbergram= funcione. Más información sobre la creación los bots de =Telegram= en su [[https://core.telegram.org/bots][página web]].
A continuación, hay que crear un archivo de configuración, que llamaremos =config.ini=. En ese archivo, introduce los siguientes parámetros: A continuación, hay que crear un archivo de configuración, que llamaremos =config.ini=. En ese archivo, introduce los siguientes parámetros:
@@ -119,6 +125,7 @@
nick = jabbergram nick = jabbergram
token = jabbergramBotTokken token = jabbergramBotTokken
group = -10,293,943,920 group = -10,293,943,920
verify_ssl = yes
#+END_SRC #+END_SRC
La única cosa que vale la pena mencionar es la sección del =token= (que es la que nos da cuando se crea el robot) y el =group=, que es ID del grupo de =Telegram=. La única cosa que vale la pena mencionar es la sección del =token= (que es la que nos da cuando se crea el robot) y el =group=, que es ID del grupo de =Telegram=.
@@ -135,9 +142,10 @@
nick = jabbergram nick = jabbergram
token = jabbergramBotTokken token = jabbergramBotTokken
group = -10293943920 120301203 group = -10293943920 120301203
verify_ssl = yes
#+END_SRC #+END_SRC
De este modo, el muc "exampleMuc@muc.nope.org" se sincronizará con el grupo "-10293943920", y "segunda@muc.sip.org" con "120301203". De este modo, el muc "exampleMuc@muc.nope.org" se sincronizará con el grupo "-10293943920", y "segunda@muc.sip.org" con "120301203". Hecho esto, solo queda ejecutarlo en la terminal: =python3 jabbergram.py config.ini=. Hay que tenerla activa siempre que se quiera que funcione, obviamente.
*** Licencia *** Licencia
#+BEGIN_SRC text #+BEGIN_SRC text
This program is free software: you can redistribute it and / or modify This program is free software: you can redistribute it and / or modify

View File

@@ -1,23 +1,64 @@
- `ended in bot, always <#ended-in-bot,-always>`__
- `+BEGIN\_SRC text <#+begin_src-text>`__
- `+END\_SRC <#+end_src>`__
ended in bot, always .. contents::
====================
:: 1 jabbergram
------------
1.1 English
~~~~~~~~~~~
1.1.1 About
^^^^^^^^^^^
With this program, it's possible to use a MuC ``XMPP`` room to talk to a group on ``Telegram`` and vice versa. The aim of this program is to be just a simple gateway, just pass text from one way to the other. Once it's stable, it probably won't have more improvements, since I don't need them.
Since version 0.1.6, Jabbergram has HTTP Upload support. If the server supports it, it will automatically upload all the files sent to the Telegram group.
1.1.2 Installation
^^^^^^^^^^^^^^^^^^
As with any program that uses python, it should be used a virtual environment (virtualenv), but that is user selectable. It's possible to use one of the next installation methods:
Install via pip:
.. code-block:: sh
:number-lines: 0
$ su -c "pip3 install jabbergram"
Clone the repository:
.. code-block:: sh
:number-lines: 0
$ git clone https://git.daemons.it/drymer/jabbergram
$ cd jabbergram
$ su -c "pip3 install -r requirements.txt"
$ su -c "python3 setup.py install"
1.1.3 Configuration
^^^^^^^^^^^^^^^^^^^
This program is simple, it even doesn't have a ``help`` menu. First thing you need to do is to create ``Telegram`` Bot. To do so, you must have a telegram account and talk to `BotFather <https://telegram.me/botfather>`_. Then, execute:
.. code-block:: sh
:number-lines: 0
/start
/newbot
YourNameBot # ended in bot, always
# then it will show your bot token, save it # then it will show your bot token, save it
/setprivacy /setprivacy
YourNameBot YourNameBot
# now press Disable # now press Disable
#+END_SRC
The =/setprivacy= option is to make the bot read all what it's said to him, not only when using commands. It's necessary to make =jabbergram= work. More info on creating =Telegram= bots at their [[https://core.telegram.org/bots][webpage]]. The ``/setprivacy`` option is to make the bot read all what it's said to him, not only when using commands. It's necessary to make ``jabbergram`` work. More info on creating ``Telegram`` bots at their `webpage <https://core.telegram.org/bots>`_.
Then, you will have to create a config file. We'll call it =config.ini=. In that file, enter the next parameters: Then, you will have to create a config file. We'll call it ``config.ini``. In that file, enter the next parameters:
.. code-block:: text
:number-lines: 0
#+BEGIN_SRC text
[config] [config]
jid = exampleJid@nope.org jid = exampleJid@nope.org
password = difficultPassword password = difficultPassword
@@ -25,21 +66,19 @@ ended in bot, always
nick = jabbergram nick = jabbergram
token = jabbergramBotTokken token = jabbergramBotTokken
group = -10293943920 group = -10293943920
#+END_SRC
The only thing worth mentioning is the =token= section, which is said to you when creating the bot, and the =group=, that is the =Telegram= group ID. The only thing worth mentioning is the ``token`` section, which is said to you when creating the bot, and the ``group``, that is the ``Telegram`` group ID.
There's no easy way to see this from telegram, so you can use the separate utility called =seeIdGroups.py=. To execute it, you only need to set the =token= parameter in the config file. You will need that somebody invite the bot to the group. Also, people on that group must send some messages, so the utility can grab it's id. It may take a couple. When you have the group ID you want, just press Ctrl-c, copy it to the config file (even the minus symbol), and the configuration will be done. There's no easy way to see this from telegram, so you can use the separate utility called ``seeIdGroups.py``. To execute it, you only need to set the ``token`` parameter in the config file. You will need that somebody invite the bot to the group. Also, people on that group must send some messages, so the utility can grab it's id. It may take a couple. When you have the group ID you want, just press Ctrl-c, copy it to the config file (even the minus symbol), and the configuration will be done.
\*\*\* Usage There only can be one configuration file. This is because 1.1.4 Usage
it can only be one bot connection, when there's more than one, message ^^^^^^^^^^^
are lost. Therefore, for linking more rooms you must "link" them in the
configuration. This is done simply by hooking jabber rooms with
Telegram:
:: There only can be one configuration file. This is because it can only be one bot connection, when there's more than one, message are lost. Therefore, for linking more rooms you must "link" them in the configuration. This is done simply by hooking jabber rooms with Telegram:
.. code-block:: sh
:number-lines: 0
#+BEGIN_SRC sh
[Config] [Config]
JID = exampleJid@nope.org JID = exampleJid@nope.org
password = difficultPassword password = difficultPassword
@@ -47,16 +86,19 @@ Telegram:
nick = jabbergram nick = jabbergram
token = jabbergramBotTokken token = jabbergramBotTokken
group = -10293943920 120301203 group = -10293943920 120301203
#+END_SRC
Thus, the example's muc "exampleMuc@muc.nope.org" syncs with the group "-10293943920" and "segunda@muc.sip.org" with "120 301203". Thus, the example's muc "exampleMuc@muc.nope.org" syncs with the group "-10293943920" and "segunda@muc.sip.org" with "120 301203".
\*\*\* License #+BEGIN\_SRC text This program is free software: you can 1.1.5 License
redistribute it and / or modify it under the terms of the GNU General ^^^^^^^^^^^^^
Public License as published by the Free Software Foundation, Either
version 3 of the License, or (At your option) any later version.
:: .. code-block:: text
:number-lines: 0
This program is free software: you can redistribute it and / or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, Either version 3 of the License, or
(At your option) any later version.
This program is distributed in the hope That it will be useful, This program is distributed in the hope That it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -65,41 +107,47 @@ version 3 of the License, or (At your option) any later version.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
Along With This Program. If not, see <http://www.gnu.org/licenses/>. Along With This Program. If not, see <http://www.gnu.org/licenses/>.
#+END_SRC
\*\* Castellano \*\*\* Acerca de Con este programa es posible utilizar 1.2 Castellano
una sala =XMPP= para hablar con un grupo de =Telegram= y viceversa. El ~~~~~~~~~~~~~~
objetivo de este programa es el de ser sólo una pasarela sencilla, sólo
tiene que pasar el texto de un lado al otro. Una vez que sea estable,
probablemente no tendrá más mejoras, ya que yo no las necesito. \*\*\*
Instalación Como con cualquier programa escrito en =Python=, deberia ser
usado en un entorno virtual (virtualenv), pero eso queda a la elección
del usuario. Es posible utilizar uno de los siguientes métodos de
instalación:
:: 1.2.1 Acerca de
^^^^^^^^^^^^^^^
Con este programa es posible utilizar una sala ``XMPP`` para hablar con un grupo de ``Telegram`` y viceversa. El objetivo de este programa es el de ser sólo una pasarela sencilla, sólo tiene que pasar el texto de un lado al otro. Una vez que sea estable, probablemente no tendrá más mejoras, ya que yo no las necesito.
Desde la versión 0.1.6, Jabbergram tiene soporte HTTP Upload. Si el servidor lo soporta, subirá automáticamente todos los archivos enviados desde el grupo de Telegram.
1.2.2 Instalación
^^^^^^^^^^^^^^^^^
Como con cualquier programa escrito en ``Python``, deberia ser usado en un entorno virtual (virtualenv), pero eso queda a la elección del usuario. Es posible utilizar uno de los siguientes métodos de instalación:
Instalar a través de ``pip``:
.. code-block:: sh
:number-lines: 0
Instalar a través de =pip=:
#+BEGIN_SRC sh
$ su -c "pip3 instalar jabbergram" $ su -c "pip3 instalar jabbergram"
#+END_SRC
Clonar el repositorio: Clonar el repositorio:
#+BEGIN_SRC sh
$ git clone git://daemons.cf/jabbergram .. code-block:: sh
:number-lines: 0
$ git clone https://git.daemons.it/drymer/jabbergram
$ cd jabbergram $ cd jabbergram
$ su -c "pip3 instalar requirements.txt -r" $ su -c "pip3 instalar -r requirements.txt"
$ su -c "python3 setup.py instalar" $ su -c "python3 setup.py install"
#+END_SRC
\*\*\* Configuración Este programa es simple, no tiene ni un menú de 1.2.3 Configuración
=ayuda=. Lo primero que hay que hacer es crear el bot de =Telegram=. ^^^^^^^^^^^^^^^^^^^
Para ello, hay que tener una cuenta de =Telegram= y hablar con
[[https://telegram.me/botfather][BotFather]]. A continuación, ejecuta:
:: Este programa es simple, no tiene ni un menú de ``ayuda``. Lo primero que hay que hacer es crear el bot de ``Telegram``. Para ello, hay que tener una cuenta de ``Telegram`` y hablar con `BotFather <https://telegram.me/botfather>`_. A continuación, ejecuta:
.. code-block:: sh
:number-lines: 0
#+BEGIN_SRC sh
/start /start
/newbot /newbot
NombreDelBot # terminado en bot, siempre NombreDelBot # terminado en bot, siempre
@@ -107,13 +155,14 @@ Para ello, hay que tener una cuenta de =Telegram= y hablar con
/setprivacy /setprivacy
NombreDelBot NombreDelBot
# Ahora hay que pulsar desactivar # Ahora hay que pulsar desactivar
#+END_SRC
La opción =/setprivacy= es para hacer que el robot pueda leer todo lo que se dice en el grupo, no sólo cuando se utilizan los comandos. Es necesario para hacer que =jabbergram= funcione. Más información sobre la creación los bots de =Telegrama= en su [[https://core.telegram.org/bots][página web]]. La opción ``/setprivacy`` es para hacer que el robot pueda leer todo lo que se dice en el grupo, no sólo cuando se utilizan los comandos. Es necesario para hacer que ``jabbergram`` funcione. Más información sobre la creación los bots de ``Telegrama`` en su `página web <https://core.telegram.org/bots>`_.
A continuación, hay que crear un archivo de configuración, que llamaremos =config.ini=. En ese archivo, introduce los siguientes parámetros: A continuación, hay que crear un archivo de configuración, que llamaremos ``config.ini``. En ese archivo, introduce los siguientes parámetros:
.. code-block:: text
:number-lines: 0
#+BEGIN_SRC text
[Config] [Config]
JID = exampleJid@nope.org JID = exampleJid@nope.org
password = difficultPassword password = difficultPassword
@@ -121,22 +170,18 @@ Para ello, hay que tener una cuenta de =Telegram= y hablar con
nick = jabbergram nick = jabbergram
token = jabbergramBotTokken token = jabbergramBotTokken
group = -10,293,943,920 group = -10,293,943,920
#+END_SRC
La única cosa que vale la pena mencionar es la sección del =token= (que es la que nos da cuando se crea el robot) y el =group=, que es ID del grupo de =Telegram=. La única cosa que vale la pena mencionar es la sección del ``token`` (que es la que nos da cuando se crea el robot) y el ``group``, que es ID del grupo de ``Telegram``.
No hay manera fácil de ver el ID desde =Telegram=, por lo que se puede utilizar el programa llamado =seeIdGroups.py=. Para ejecutarlo sólo es necesario establecer el parámetro =token= del archivo de configuración. Necesitarás que alguien invite al bot al grupo. Además, las personas de ese grupo deben enviar algunos mensajes, para que el programa pueda coger su ID. Puede llevar unos segundos el que aparezcan los mensajes. Cuando se tenga el ID de grupo que se quiere, sólo hay que pulsar Ctrl-c, copiarlo en el archivo de configuración (incluido el simbolo menos), y la configuración estará terminada. No hay manera fácil de ver el ID desde ``Telegram``, por lo que se puede utilizar el programa llamado ``seeIdGroups.py``. Para ejecutarlo sólo es necesario establecer el parámetro ``token`` del archivo de configuración. Necesitarás que alguien invite al bot al grupo. Además, las personas de ese grupo deben enviar algunos mensajes, para que el programa pueda coger su ID. Puede llevar unos segundos el que aparezcan los mensajes. Cuando se tenga el ID de grupo que se quiere, sólo hay que pulsar Ctrl-c, copiarlo en el archivo de configuración (incluido el simbolo menos), y la configuración estará terminada.
\*\*\* Uso Sólo puede haber un archivo de configuración. Esto es debido 1.2.4 Uso
a que sólo puede haber una conexión del bot, cuando hay más de una se ^^^^^^^^^
pierden mensajes. Por lo tanto, para linkear más salas hay que
"linkearlas" en la configuración. Esto se hace, simplemente, enganchando
las salas de jabber con las de telegram:
+BEGIN\_SRC text Sólo puede haber un archivo de configuración. Esto es debido a que sólo puede haber una conexión del bot, cuando hay más de una se pierden mensajes. Por lo tanto, para linkear más salas hay que "linkearlas" en la configuración. Esto se hace, simplemente, enganchando las salas de jabber con las de telegram:
================
:: .. code-block:: text
:number-lines: 0
[Config] [Config]
JID = exampleJid@nope.org JID = exampleJid@nope.org
@@ -146,17 +191,18 @@ las salas de jabber con las de telegram:
token = jabbergramBotTokken token = jabbergramBotTokken
group = -10293943920 120301203 group = -10293943920 120301203
+END\_SRC De este modo, el muc "exampleMuc@muc.nope.org" se sincronizará con el grupo "-10293943920", y "segunda@muc.sip.org" con "120301203".
=========
De este modo, el muc "exampleMuc@muc.nope.org" se sincronizará con el 1.2.5 Licencia
grupo "-10293943920", y "segunda@muc.sip.org" con "120301203". \*\*\* ^^^^^^^^^^^^^^
Licencia #+BEGIN\_SRC text This program is free software: you can
redistribute it and / or modify it under the terms of the GNU General
Public License as published by the Free Software Foundation, Either
version 3 of the License, or (At your option) any later version.
:: .. code-block:: text
:number-lines: 0
This program is free software: you can redistribute it and / or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, Either version 3 of the License, or
(At your option) any later version.
This program is distributed in the hope That it will be useful, This program is distributed in the hope That it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -165,4 +211,3 @@ version 3 of the License, or (At your option) any later version.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
Along With This Program. If not, see <http://www.gnu.org/licenses/>. Along With This Program. If not, see <http://www.gnu.org/licenses/>.
#+END_SRC

View File

@@ -1,21 +1,44 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import configparser
import logging
from sys import argv
from threading import Thread
from time import sleep
from xml.dom import minidom
import sleekxmpp import sleekxmpp
import telegram import telegram
import configparser from sleekxmpp.xmlstream.stanzabase import ElementBase
from threading import Thread
from queue import Queue
from telegram.error import NetworkError, Unauthorized from telegram.error import NetworkError, Unauthorized
from time import sleep
from sys import argv
from sys import exit
class EchoBot(sleekxmpp.ClientXMPP): try:
def __init__(self, jid, password, rooms, nick, token, groups): import requests
except:
logging.error("HTTP Upload support disabled.")
class Request(ElementBase):
"""Special class to create http_upload requests."""
namespace = 'urn:xmpp:http:upload'
name = 'request'
plugin_attrib = 'request'
interfaces = set(('filename', 'size'))
sub_interfaces = interfaces
class Jabbergram(sleekxmpp.ClientXMPP):
"""Main object."""
def __init__(self, jid, password, rooms, nick, token, groups, verify_ssl):
"""
Executed when the class is initialized. It adds session handlers, muc
handlers and send the telegram reading function and the HTTP upload
initializing functions to their respective threads.
"""
# XMPP # XMPP
super(EchoBot, self).__init__(jid, password) super(Jabbergram, self).__init__(jid, password)
self.add_event_handler('session_start', self.start) self.add_event_handler('session_start', self.start)
self.add_event_handler('groupchat_message', self.muc_message) self.add_event_handler('groupchat_message', self.muc_message)
@@ -23,6 +46,8 @@ class EchoBot(sleekxmpp.ClientXMPP):
self.nick = nick self.nick = nick
self.token = token self.token = token
self.xmpp_users = {} self.xmpp_users = {}
self.jid = jid
self.verify_ssl = verify_ssl
for muc in self.muc_rooms: for muc in self.muc_rooms:
self.add_event_handler("muc::%s::got_online" % muc, self.add_event_handler("muc::%s::got_online" % muc,
@@ -35,7 +60,13 @@ class EchoBot(sleekxmpp.ClientXMPP):
self.bot = telegram.Bot(self.token) self.bot = telegram.Bot(self.token)
self.telegram_users = {} self.telegram_users = {}
# meter el conector del tg en un hilo # initialize http upload on a thread since its needed to be connected
# to xmpp
t = Thread(target=self.init_http)
t.daemon = True
t.start()
# put tg connector in a thread
t = Thread(target=self.read_tg) t = Thread(target=self.read_tg)
t.daemon = True t.daemon = True
t.start() t.start()
@@ -43,53 +74,182 @@ class EchoBot(sleekxmpp.ClientXMPP):
print('Please wait a couple of minutes until it\'s correctly ' print('Please wait a couple of minutes until it\'s correctly '
'connected') 'connected')
def init_http(self):
"""
Initializes HTTP upload support. Sends a discovery stanza to the server
to find the HTTP upload component and asks for the max size a file can
be.
"""
self.http_upload = self.HttpUpload(self)
self.component = self.http_upload.discovery()
if self.component:
xml = self.http_upload.disco_info(self.component)
xml = minidom.parseString(str(xml))
self.max_size = int(xml.getElementsByTagName('value')
[1].firstChild.data)
else:
try:
self.component = self.jid.split('@')[1]
xml = self.http_upload.disco_info(self.component)
xml = minidom.parseString(str(xml))
self.max_size = int(xml.getElementsByTagName('value')
[1].firstChild.data)
except:
self.max_size = None
def read_tg(self): def read_tg(self):
"""Main telegram function."""
update_id = 0 update_id = 0
# wait until http_upload has been tested
sleep(5)
while True: while True:
try: try:
for update in self.bot.getUpdates(offset=update_id, for update in self.bot.getUpdates(offset=update_id,
timeout=10): timeout=10):
message = update.message.text name = ''
user = str(update.message.from_user.username) size = 0
if update.edited_message:
update_id = update.update_id + 1
continue
if update.message.from_user:
user = update.message.from_user.username
# sometimes there's no user. weird, but it happens # sometimes there's no user. weird, but it happens
if not user: if not user:
user = str(update.message.from_user.first_name) user = update.message.from_user.first_name
# sometimes there's no user. weird, but it happens
elif update.message['from']:
user = str(update.message['from'].first_name)
if update.message.audio or update.message.document or \
update.message.photo or update.message.video \
or update.message.voice or update.message.sticker:
# proceed only if http upload is available
if self.max_size is not None:
if update.message.audio:
d_file = update.message.audio
ext = '.ogg'
size = d_file.file_size
elif update.message.document:
d_file = update.message.document
ext = ''
size = d_file.file_size
elif update.message.photo:
d_file = update.message.photo[-1]
ext = '.jpg'
size = d_file.file_size
elif update.message.video:
d_file = update.message.video[-1]
ext = '.mp4'
size = d_file.file_size
elif update.message.voice:
d_file = update.message.voice
ext = '.ogg'
size = d_file.file_size
elif update.message.sticker:
d_file = update.message.sticker
ext = '.png'
size = d_file.file_size
if self.max_size >= int(size):
t_file = self.bot.getFile(d_file.file_id)
f_name = '/tmp/' + d_file.file_id + ext
t_file.download(f_name)
url = self.http_upload.upload(
self.component,
self.verify_ssl,
f_name, size)
if update.message.caption:
message = update.message.caption + ' '
else:
message = 'File uploaded: '
message += url
else:
message = 'A file has been uploaded to Telegr'\
'am, but is too big.'
else:
message = 'A file has been uploaded to Telegram,'\
'but the XMPP server doesn\'t support H'\
'TTP Upload.'
elif update.message.new_chat_member:
message = 'This user has joined the group.'
elif update.message.left_chat_member:
message = 'This user has left the group.'
elif update.message.new_chat_title:
message = 'The group\'s title has changed: ' + \
update.message.new_chat_title
elif update.message.new_chat_photo:
message = 'The group\'s photo has changed.'
else:
if update.message.reply_to_message:
name = update.message.reply_to_message.from_user\
.username
if name != self.bot.username:
message = name + ': ' + \
update.message.reply_to_message.text
else:
message = update.message.reply_to_message.text
else:
message = update.message.text
if name:
msg = message + ' <- ' + user + ": " + \
update.message.text
else:
msg = user + ": " + message msg = user + ": " + message
chat_id = update.message.chat_id
if message and str(chat_id) in self.groups: if update.message.chat.type == 'supergroup' and \
index = self.groups.index(str(chat_id)) update.message.chat.username:
chat = '@' + update.message.chat.username
else:
chat = str(update.message.chat.id)
if chat not in self.groups:
chat = str(update.message.chat_id)
if message and chat in self.groups:
index = self.groups.index(chat)
receiver = self.muc_rooms[index] receiver = self.muc_rooms[index]
if chat_id in self.telegram_users: if chat in self.telegram_users:
if user not in self.telegram_users[chat_id]: if user not in self.telegram_users[chat]:
self.telegram_users[chat_id] += ' ' + user self.telegram_users[chat] += ' ' + user
else: else:
self.telegram_users[chat_id] = ' ' + user self.telegram_users[chat] = ' ' + user
if message == '.users': if message == '.users':
index = self.groups.index(str(chat_id)) self.say_users('telegram', receiver, chat)
muc = self.muc_rooms[index] elif message == '.help':
self.say_users('telegram', muc, chat_id) self.say_help('telegram', receiver, chat)
elif message == '.where':
self.say_where('telegram', receiver, chat)
else: else:
self.send_message(mto=receiver, mbody=msg, self.send_message(mto=receiver, mbody=msg,
mtype='groupchat') mtype='groupchat')
update_id = update.update_id + 1 update_id = update.update_id + 1
except NetworkError as e: except NetworkError as e:
print(e)
sleep(1) sleep(1)
except Unauthorized: except Unauthorized as e:
print(e)
sleep(1) sleep(1)
except Exception as e: except Exception as e:
update_id += 1
print(e) print(e)
def start(self, event): def start(self, event):
"""Does some initial setup for XMPP and joins all mucs."""
self.get_roster() self.get_roster()
self.send_presence() self.send_presence()
@@ -97,18 +257,23 @@ class EchoBot(sleekxmpp.ClientXMPP):
self.plugin['xep_0045'].joinMUC(muc, self.nick, wait=True) self.plugin['xep_0045'].joinMUC(muc, self.nick, wait=True)
def muc_message(self, msg): def muc_message(self, msg):
"""Muc message's handler."""
muc_room = str(msg['from']).split('/')[0] muc_room = str(msg['from']).split('/')[0]
index = self.muc_rooms.index(muc_room) index = self.muc_rooms.index(muc_room)
tg_group = self.groups[index] tg_group = self.groups[index]
if msg['body'] == '.users': if msg['body'] == '.users':
self.say_users('xmpp', muc_room, tg_group) self.say_users('xmpp', muc_room, tg_group)
elif msg['body'] == '.help':
self.say_help('xmpp', muc_room, tg_group)
elif msg['body'] == '.where':
self.say_where('xmpp', muc_room, tg_group)
elif msg['mucnick'] != self.nick: elif msg['mucnick'] != self.nick:
message = str(msg['from']).split('/')[1] + ': ' + str(msg['body']) message = str(msg['from']).split('/')[1] + ': ' + str(msg['body'])
self.bot.sendMessage(tg_group, text=message) self.bot.sendMessage(tg_group, text=message)
def muc_online(self, presence): def muc_online(self, presence):
"""Muc presence's handler."""
user = presence['muc']['nick'] user = presence['muc']['nick']
muc = presence['from'].bare muc = presence['from'].bare
@@ -119,6 +284,7 @@ class EchoBot(sleekxmpp.ClientXMPP):
self.xmpp_users[muc] = [presence['muc']['nick']] self.xmpp_users[muc] = [presence['muc']['nick']]
def muc_offline(self, presence): def muc_offline(self, presence):
"""Muc presence's handler."""
user = presence['muc']['nick'] user = presence['muc']['nick']
muc = presence['from'].bare muc = presence['from'].bare
@@ -126,37 +292,120 @@ class EchoBot(sleekxmpp.ClientXMPP):
self.xmpp_users[muc].remove(presence['muc']['nick']) self.xmpp_users[muc].remove(presence['muc']['nick'])
def say_users(self, service, muc, group): def say_users(self, service, muc, group):
xmpp_users = "" """It returns the users on XMPP or Telegram."""
tg_users = "" if service == 'xmpp':
group = int(group)
if muc in self.xmpp_users:
for i in self.xmpp_users[muc]:
xmpp_users = xmpp_users + ' _' + i
else:
xmpp_users = ""
msg1 = 'XMPP Users:' + xmpp_users
if group in self.telegram_users: if group in self.telegram_users:
tg_users = self.telegram_users[group] tg_users = self.telegram_users[group]
else: else:
tg_users = "" tg_users = ""
msg2 = 'Telegram Users:' + tg_users msg = 'Telegram Users:' + tg_users
message = msg1 + '\n' + msg2 self.send_message(mto=muc, mbody=msg, mtype='groupchat')
if service == 'xmpp':
self.send_message(mto=muc, mbody=message, mtype='groupchat')
# arreglar el .users por el lado de tg
elif service == 'telegram': elif service == 'telegram':
self.bot.sendMessage(group, text=message) xmpp_users = ""
if muc in self.xmpp_users:
for i in self.xmpp_users[muc]:
xmpp_users = xmpp_users + ' ' + i
else:
xmpp_users = ""
msg = 'XMPP Users:' + xmpp_users
self.bot.sendMessage(group, text=msg)
def say_help(self, service, muc, group):
"""Help command."""
msg = 'Hi, I\'m ' + self.bot.username + '. I have two commands : ".us'\
'ers" and ".where".'
if service == 'xmpp':
self.send_message(mto=muc, mbody=msg, mtype='groupchat')
elif service == 'telegram':
self.bot.sendMessage(group, text=msg)
def say_where(self, service, muc, group):
"""Returns Telegram's group location if it's public."""
if service == 'xmpp':
if '@' in group:
msg = 'I\'m on http://telegram.me/' + group.split('@')[1] + '.'
else:
msg = 'Sorry, I\'m on a private group, you\'ll have to ask fo'\
'r an invitation.'
self.send_message(mto=muc, mbody=msg, mtype='groupchat')
elif service == 'telegram':
msg = 'I\'m on ' + muc + '.'
self.bot.sendMessage(group, text=msg)
class HttpUpload():
"""HTTP upload main class."""
def __init__(self, parent_self):
"""Init... Yep."""
self.parent_self = parent_self
def discovery(self):
"""Discovers all server's components."""
disco = sleekxmpp.basexmpp.BaseXMPP.Iq(self.parent_self)
disco['query'] = "http://jabber.org/protocol/disco#items"
disco['type'] = 'get'
disco['from'] = self.parent_self.jid
disco['to'] = self.parent_self.jid.split('@')[1]
d = disco.send(timeout=30)
xml = minidom.parseString(str(d))
item = xml.getElementsByTagName('item')
for component in item:
component = component.getAttribute('jid')
info = self.disco_info(component)
if "urn:xmpp:http:upload" in info:
http_upload_component = component
break
else:
http_upload_component = ""
return http_upload_component
def disco_info(self, component):
"""Discovers HTTP upload components attributes."""
info = sleekxmpp.basexmpp.BaseXMPP.Iq(self.parent_self)
info['query'] = "http://jabber.org/protocol/disco#info"
info['type'] = 'get'
info['from'] = self.parent_self.jid
info['to'] = component
response = str(info.send(timeout=30))
return response
def upload(self, component, verify_ssl, u_file, size):
"""Uploads to HTTP upload."""
peticion = Request()
peticion['filename'] = u_file.split('/')[-1]
peticion['size'] = str(size)
iq = sleekxmpp.basexmpp.BaseXMPP.Iq(self.parent_self)
iq.set_payload(peticion)
iq['type'] = 'get'
iq['to'] = component
iq['from'] = self.parent_self.jid
send = iq.send(timeout=30)
xml = minidom.parseString(str(send))
put_url = xml.getElementsByTagName('put')[0].firstChild.data
if verify_ssl == 'False':
req = requests.put(put_url, data=open(u_file, 'rb'),
verify=False)
else:
req = requests.put(put_url, data=open(u_file, 'rb'))
return put_url
if __name__ == '__main__': if __name__ == '__main__':
# parsear config # parse config
config = [] config = []
parser = configparser.SafeConfigParser() parser = configparser.SafeConfigParser()
@@ -168,15 +417,17 @@ if __name__ == '__main__':
for name, value in parser.items('config'): for name, value in parser.items('config'):
config.append(value) config.append(value)
# asignar valores para el bot # assign values for the bot
jid = config[0] jid = config[0]
password = config[1] password = config[1]
muc_rooms = config[2] muc_rooms = config[2]
nick = config[3] nick = config[3]
token = config[4] token = config[4]
groups = config[5] groups = config[5]
verify_ssl = config[6]
xmpp = EchoBot(jid, password, muc_rooms, nick, token, groups) xmpp = Jabbergram(jid, password, muc_rooms, nick, token, groups,
verify_ssl)
xmpp.register_plugin('xep_0045') xmpp.register_plugin('xep_0045')
if xmpp.connect(): if xmpp.connect():
@@ -184,5 +435,3 @@ if __name__ == '__main__':
print("Done") print("Done")
else: else:
print("Unable to connect.") print("Unable to connect.")
# Vols un gram nen?

View File

@@ -1,2 +1,3 @@
sleekxmpp >= 1.3.1 sleekxmpp >= 1.3.2
python-telegram-bot >= 4.0.3 python-telegram-bot >= 6.1.0
requests >= 2.11.1

View File

@@ -30,6 +30,9 @@ printed = []
while True: while True:
try: try:
for update in bot.getUpdates(offset=update_id, timeout=10): for update in bot.getUpdates(offset=update_id, timeout=10):
if update.edited_message:
update_id = update.update_id + 1
continue
chat_id = update.message.chat_id chat_id = update.message.chat_id
chat_title = update.message chat_title = update.message
if chat_id not in printed: if chat_id not in printed:

View File

@@ -2,7 +2,7 @@
from setuptools import setup from setuptools import setup
VERSION = '0.1.5' VERSION = '0.1.7'
setup(name='jabbergram', setup(name='jabbergram',
version=VERSION, version=VERSION,
@@ -10,13 +10,14 @@ setup(name='jabbergram',
long_description=open('README.rst', encoding='utf-8').read(), long_description=open('README.rst', encoding='utf-8').read(),
author='drymer', author='drymer',
author_email='drymer@autistici.org', author_email='drymer@autistici.org',
url='http://daemons.cf/cgit/jabbergram/about/', url='http://git.daemons.it/drymer/jabbergram/about/',
download_url='http://daemons.cf/cgit/jabbergram/snapshot/jabbergram-' + VERSION + '.tar.gz', download_url='https://git.daemons.it/drymer/jabbergram/archive/' + VERSION + '.tar.gz',
scripts=['jabbergram.py'], scripts=['jabbergram.py'],
license="GPLv3", license="GPLv3",
install_requires=[ install_requires=[
"sleekxmpp>=1.3.1", "sleekxmpp>=1.3.2",
"python-telegram-bot>=4.0.3", "python-telegram-bot>=6.1.0",
"requests>=2.11.1",
], ],
classifiers=["Development Status :: 4 - Beta", classifiers=["Development Status :: 4 - Beta",
"Programming Language :: Python", "Programming Language :: Python",