4 Commits

Author SHA1 Message Date
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
6 changed files with 377 additions and 150 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:
@@ -114,6 +116,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:
@@ -126,8 +130,8 @@ Clonar el repositorio:
$ git clone git://daemons.cf/jabbergram $ git clone git://daemons.cf/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"
### Configuración<a id="orgheadline9"></a> ### Configuración<a id="orgheadline9"></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:
@@ -79,6 +81,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:
@@ -91,8 +95,8 @@
#+BEGIN_SRC sh #+BEGIN_SRC sh
$ git clone git://daemons.cf/jabbergram $ git clone git://daemons.cf/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 #+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:

View File

@@ -1,168 +1,213 @@
- `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
------------
# then it will show your bot token, save it 1.1 English
/setprivacy ~~~~~~~~~~~
YourNameBot
# 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]]. 1.1.1 About
^^^^^^^^^^^
Then, you will have to create a config file. We'll call it =config.ini=. In that file, enter the next parameters: 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.
#+BEGIN_SRC text 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.
[config]
jid = exampleJid@nope.org
password = difficultPassword
muc_room = exampleMuc@muc.nope.org
nick = jabbergram
token = jabbergramBotTokken
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. 1.1.2 Installation
^^^^^^^^^^^^^^^^^^
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. 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:
\*\*\* Usage There only can be one configuration file. This is because Install via pip:
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 $ su -c "pip3 install jabbergram"
[Config]
JID = exampleJid@nope.org
password = difficultPassword
muc_room = exampleMuc@muc.nope.org segunda@muc.sip.org
nick = jabbergram
token = jabbergramBotTokken
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". Clone the repository:
\*\*\* License #+BEGIN\_SRC text This program is free software: you can .. code-block:: sh
redistribute it and / or modify it under the terms of the GNU General :number-lines: 0
Public License as published by the Free Software Foundation, Either
version 3 of the License, or (At your option) any later version.
:: $ git clone git://daemons.cf/jabbergram
$ cd jabbergram
$ su -c "pip3 install -r requirements.txt"
$ su -c "python3 setup.py install"
This program is distributed in the hope That it will be useful, 1.1.3 Configuration
but WITHOUT ANY WARRANTY; without even the implied warranty of ^^^^^^^^^^^^^^^^^^^
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License 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:
Along With This Program. If not, see <http://www.gnu.org/licenses/>.
#+END_SRC
\*\* Castellano \*\*\* Acerca de Con este programa es posible utilizar .. code-block:: sh
una sala =XMPP= para hablar con un grupo de =Telegram= y viceversa. El :number-lines: 0
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:
:: /start
/newbot
YourNameBot # ended in bot, always
# then it will show your bot token, save it
/setprivacy
YourNameBot
# now press Disable
Instalar a través de =pip=: 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>`_.
#+BEGIN_SRC sh
$ su -c "pip3 instalar jabbergram"
#+END_SRC
Clonar el repositorio: Then, you will have to create a config file. We'll call it ``config.ini``. In that file, enter the next parameters:
#+BEGIN_SRC sh
$ git clone git://daemons.cf/jabbergram
$ cd jabbergram
$ su -c "pip3 instalar requirements.txt -r"
$ su -c "python3 setup.py instalar"
#+END_SRC
\*\*\* Configuración Este programa es simple, no tiene ni un menú de .. code-block:: text
=ayuda=. Lo primero que hay que hacer es crear el bot de =Telegram=. :number-lines: 0
Para ello, hay que tener una cuenta de =Telegram= y hablar con
[[https://telegram.me/botfather][BotFather]]. A continuación, ejecuta:
:: [config]
jid = exampleJid@nope.org
password = difficultPassword
muc_room = exampleMuc@muc.nope.org
nick = jabbergram
token = jabbergramBotTokken
group = -10293943920
#+BEGIN_SRC sh 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.
/start
/newbot
NombreDelBot # terminado en bot, siempre
# A continuación, se mostrará el token del bot, hay que guardarlo
/setprivacy
NombreDelBot
# 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]]. 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.
A continuación, hay que crear un archivo de configuración, que llamaremos =config.ini=. En ese archivo, introduce los siguientes parámetros: 1.1.4 Usage
^^^^^^^^^^^
#+BEGIN_SRC text 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:
[Config]
JID = exampleJid@nope.org
password = difficultPassword
muc_room = exampleMuc@muc.nope.org
nick = jabbergram
token = jabbergramBotTokken
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=. .. code-block:: sh
:number-lines: 0
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. [Config]
JID = exampleJid@nope.org
password = difficultPassword
muc_room = exampleMuc@muc.nope.org segunda@muc.sip.org
nick = jabbergram
token = jabbergramBotTokken
group = -10293943920 120301203
\*\*\* Uso Sólo puede haber un archivo de configuración. Esto es debido Thus, the example's muc "exampleMuc@muc.nope.org" syncs with the group "-10293943920" and "segunda@muc.sip.org" with "120 301203".
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 1.1.5 License
================ ^^^^^^^^^^^^^
:: .. code-block:: text
:number-lines: 0
[Config] This program is free software: you can redistribute it and / or modify
JID = exampleJid@nope.org it under the terms of the GNU General Public License as published by
password = difficultPassword the Free Software Foundation, Either version 3 of the License, or
muc_room = exampleMuc@muc.nope.org segunda@muc.sip.org (At your option) any later version.
nick = jabbergram
token = jabbergramBotTokken
group = -10293943920 120301203
+END\_SRC This program is distributed in the hope That it will be useful,
========= but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
De este modo, el muc "exampleMuc@muc.nope.org" se sincronizará con el You should have received a copy of the GNU General Public License
grupo "-10293943920", y "segunda@muc.sip.org" con "120301203". \*\*\* Along With This Program. If not, see <http://www.gnu.org/licenses/>.
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.
:: 1.2 Castellano
~~~~~~~~~~~~~~
This program is distributed in the hope That it will be useful, 1.2.1 Acerca de
but WITHOUT ANY WARRANTY; without even the implied warranty of ^^^^^^^^^^^^^^^
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License 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.
Along With This Program. If not, see <http://www.gnu.org/licenses/>.
#+END_SRC 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
$ su -c "pip3 instalar jabbergram"
Clonar el repositorio:
.. code-block:: sh
:number-lines: 0
$ git clone git://daemons.cf/jabbergram
$ cd jabbergram
$ su -c "pip3 instalar -r requirements.txt"
$ su -c "python3 setup.py install"
1.2.3 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 `BotFather <https://telegram.me/botfather>`_. A continuación, ejecuta:
.. code-block:: sh
:number-lines: 0
/start
/newbot
NombreDelBot # terminado en bot, siempre
# A continuación, se mostrará el token del bot, hay que guardarlo
/setprivacy
NombreDelBot
# 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>`_.
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
[Config]
JID = exampleJid@nope.org
password = difficultPassword
muc_room = exampleMuc@muc.nope.org
nick = jabbergram
token = jabbergramBotTokken
group = -10,293,943,920
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.
1.2.4 Uso
^^^^^^^^^
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]
JID = exampleJid@nope.org
password = difficultPassword
muc_room = exampleMuc@muc.nope.org segunda@muc.sip.org
nick = jabbergram
token = jabbergramBotTokken
group = -10293943920 120301203
De este modo, el muc "exampleMuc@muc.nope.org" se sincronizará con el grupo "-10293943920", y "segunda@muc.sip.org" con "120301203".
1.2.5 Licencia
^^^^^^^^^^^^^^
.. 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,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
Along With This Program. If not, see <http://www.gnu.org/licenses/>.

View File

@@ -1,6 +1,10 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
try:
import requests
except:
print("HTTP Upload support disabled.")
import sleekxmpp import sleekxmpp
import telegram import telegram
import configparser import configparser
@@ -10,12 +14,22 @@ from telegram.error import NetworkError, Unauthorized
from time import sleep from time import sleep
from sys import argv from sys import argv
from sys import exit from sys import exit
from sleekxmpp.xmlstream.stanzabase import ElementBase
from sleekxmpp.stanza.iq import Iq
from xml.dom import minidom
class EchoBot(sleekxmpp.ClientXMPP): class Request(ElementBase):
namespace = 'urn:xmpp:http:upload'
name = 'request'
plugin_attrib = 'request'
interfaces = set(('filename', 'size'))
sub_interfaces = interfaces
class Jabbergram(sleekxmpp.ClientXMPP):
def __init__(self, jid, password, rooms, nick, token, groups): def __init__(self, jid, password, rooms, nick, token, groups):
# 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,40 +37,132 @@ 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
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,
self.muc_online) self.muc_online)
self.add_event_handler("muc::%s::got_offline" % muc, self.add_event_handler("muc::%s::got_offline" % muc,
self.muc_offline) self.muc_offline)
# Telegram # Telegram
self.groups = groups.split() self.groups = groups.split()
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()
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):
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):
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
if update.message.audio or update.message.document or \
update.message.photo or update.message.video \
or update.message.voice:
# 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
if self.max_size >= size:
t_file = self.bot.getFile(d_file.file_id)
name = '/tmp/' + d_file.file_id + ext
t_file.download(name)
url = self.http_upload.upload(
self.component,
'', name, size)
if update.message.caption:
message = update.message.caption + ' '
else:
message = 'File uploaded: '
message += url
else:
message = 'A file has been uploaded to Telegra'
'm, but is too big.'
else:
message = 'A file has been uploaderd to Telegram, '
'but the XMPP server doesn\'t support HTTP 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 haschanged.'
else:
message = update.message.text
user = str(update.message.from_user.username) user = str(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 = str(update.message.from_user.first_name)
# even weirder is that username or first_name exists
# let's take last_name
if not user:
user = str(update.message.from_user.last_name)
msg = user + ": " + message msg = user + ": " + message
chat_id = update.message.chat_id chat_id = update.message.chat_id
@@ -76,19 +182,21 @@ class EchoBot(sleekxmpp.ClientXMPP):
self.say_users('telegram', muc, chat_id) self.say_users('telegram', muc, chat_id)
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:
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):
self.get_roster() self.get_roster()
self.send_presence() self.send_presence()
@@ -149,14 +257,78 @@ class EchoBot(sleekxmpp.ClientXMPP):
if service == 'xmpp': if service == 'xmpp':
self.send_message(mto=muc, mbody=message, mtype='groupchat') 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) self.bot.sendMessage(group, text=message)
class HttpUpload():
def __init__(self, parent_self):
self.parent_self = parent_self
def discovery(self):
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):
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
return str(info.send(timeout=30))
def upload(self, component, verify_ssl, u_file, size):
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
verify_ssl = ''
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,7 +340,7 @@ 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]
@@ -176,7 +348,7 @@ if __name__ == '__main__':
token = config[4] token = config[4]
groups = config[5] groups = config[5]
xmpp = EchoBot(jid, password, muc_rooms, nick, token, groups) xmpp = Jabbergram(jid, password, muc_rooms, nick, token, groups)
xmpp.register_plugin('xep_0045') xmpp.register_plugin('xep_0045')
if xmpp.connect(): if xmpp.connect():

View File

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

View File

@@ -2,7 +2,7 @@
from setuptools import setup from setuptools import setup
VERSION = '0.1.5' VERSION = '0.1.6'
setup(name='jabbergram', setup(name='jabbergram',
version=VERSION, version=VERSION,
@@ -17,6 +17,7 @@ setup(name='jabbergram',
install_requires=[ install_requires=[
"sleekxmpp>=1.3.1", "sleekxmpp>=1.3.1",
"python-telegram-bot>=4.0.3", "python-telegram-bot>=4.0.3",
"requests>=2.11.1",
], ],
classifiers=["Development Status :: 4 - Beta", classifiers=["Development Status :: 4 - Beta",
"Programming Language :: Python", "Programming Language :: Python",