├── matrigram ├── __init__.py ├── helper.py ├── client.py └── bot.py ├── docs ├── logo.jpg ├── tb_commands ├── code.rst ├── _templates │ └── badges.html ├── index.rst ├── quickstart.rst ├── commands.rst ├── Makefile └── conf.py ├── config.json.example ├── requirements.txt ├── tests ├── init_config.sh ├── matrigram_test.py └── helper_test.py ├── tox.ini ├── .travis.yml ├── LICENSE ├── README.md └── matrigram_main.py /matrigram/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/logo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/galpressman/matrigram/HEAD/docs/logo.jpg -------------------------------------------------------------------------------- /config.json.example: -------------------------------------------------------------------------------- 1 | { 2 | "telegram_token": "tg_token", 3 | "server": "http://matrix.org" 4 | } 5 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | telepot 2 | requests 3 | git+git://github.com/matrix-org/matrix-python-sdk@master#egg=matrix_client 4 | -------------------------------------------------------------------------------- /tests/init_config.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # This test assumes you have $TG_TOKEN evironment variable defined 3 | 4 | set -e 5 | set -x 6 | 7 | CONFIG_FILE="$HOME/.matrigramconfig" 8 | 9 | cp -f config.json.example $CONFIG_FILE 10 | set +x 11 | sed -i -- "s/tg_token/""${TG_TOKEN}""/g" $CONFIG_FILE 12 | -------------------------------------------------------------------------------- /docs/tb_commands: -------------------------------------------------------------------------------- 1 | login - /login 2 | logout - /logout 3 | join - /join 4 | leave - /leave 5 | discover - /discover_rooms 6 | focus - /focus 7 | status - /status 8 | create_room - /create_room [invitees] 9 | set_name - /setname 10 | emote = /me 11 | -------------------------------------------------------------------------------- /tests/matrigram_test.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | import shlex 3 | import time 4 | 5 | 6 | class TestMatrigram(object): 7 | def test_one(self): 8 | cmd = 'python matrigram_main.py' 9 | p = subprocess.Popen(shlex.split(cmd)) 10 | 11 | time.sleep(5) 12 | 13 | assert not p.poll(), "matrigram did not boot" 14 | p.terminate() 15 | p.wait() 16 | -------------------------------------------------------------------------------- /docs/code.rst: -------------------------------------------------------------------------------- 1 | Matrigram code 2 | ============== 3 | 4 | Bot 5 | ^^^ 6 | .. automodule:: matrigram.bot 7 | .. autoclass:: MatrigramBot 8 | :members: 9 | :private-members: 10 | 11 | Client 12 | ^^^^^^ 13 | .. automodule:: matrigram.client 14 | .. autoclass:: MatrigramClient 15 | :members: 16 | :private-members: 17 | 18 | Helper 19 | ^^^^^^ 20 | .. automodule:: matrigram.helper 21 | :members: -------------------------------------------------------------------------------- /docs/_templates/badges.html: -------------------------------------------------------------------------------- 1 | 2 |

Github repository

3 |

Github repository

4 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | skipsdist = True 3 | envlist = py27 4 | 5 | [testenv] 6 | setenv = PYTHONPATH=. 7 | deps = 8 | pytest 9 | -rrequirements.txt 10 | flake8 11 | pylint 12 | commands= 13 | py.test 14 | flake8 --max-line-length=100 matrigram matrigram_main.py 15 | pylint --errors-only matrigram matrigram_main.py 16 | - pylint --disable=too-many-instance-attributes,redefined-builtin,ungrouped-imports,too-many-public-methods,fixme,missing-docstring,invalid-name,protected-access matrigram matrigram_main.py 17 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. matrigram documentation master file, created by 2 | sphinx-quickstart on Tue Dec 20 11:09:38 2016. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | matrigram 7 | ========= 8 | 9 | The bridge between `matrix `_ and `telegram `_. 10 | 11 | Contents: 12 | 13 | .. toctree:: 14 | :maxdepth: 2 15 | 16 | quickstart 17 | commands 18 | code 19 | 20 | 21 | Indices and tables 22 | ================== 23 | 24 | * :ref:`genindex` 25 | * :ref:`modindex` 26 | * :ref:`search` 27 | 28 | -------------------------------------------------------------------------------- /tests/helper_test.py: -------------------------------------------------------------------------------- 1 | from matrigram import helper 2 | 3 | 4 | def test_chunks(): 5 | l = [] 6 | for i in range(10): 7 | l.append(i) 8 | 9 | chunks = helper.chunks(l, 4) 10 | chunks_list = [chunk for chunk in chunks] 11 | 12 | assert chunks_list[0] == [0, 1, 2, 3] 13 | assert chunks_list[1] == [4, 5, 6, 7] 14 | assert chunks_list[2] == [8, 9] 15 | 16 | 17 | def test_list_to_str(): 18 | l = ['room1', 'room2', 'room3'] 19 | 20 | assert helper.list_to_nice_str(l) == 'room1, room2, room3' 21 | 22 | 23 | def test_list_to_nice_lines(): 24 | l = ['room1', 'room2', 'room3'] 25 | 26 | assert helper.list_to_nice_lines(l) == 'room1\nroom2\nroom3' 27 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "2.7" 4 | env: 5 | - PYTHONPATH=. 6 | # command to install dependencies 7 | install: 8 | - sudo apt-get install spell 9 | - pip install -r requirements.txt 10 | - pip install flake8 11 | - pip install pylint 12 | - pip install pytest 13 | - sh ./tests/init_config.sh 14 | # command to run tests 15 | script: 16 | - flake8 --max-line-length=100 matrigram matrigram_main.py 17 | - pylint --errors-only matrigram matrigram_main.py 18 | - py.test 19 | after_script: 20 | - pylint --disable=too-many-instance-attributes,redefined-builtin,ungrouped-imports,too-many-public-methods,fixme,missing-docstring,invalid-name,protected-access matrigram matrigram_main.py 21 | - spell <(git log -1 --pretty=%B) 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 matrigram 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /docs/quickstart.rst: -------------------------------------------------------------------------------- 1 | Quick start 2 | =========== 3 | 4 | After the server is running, switch to your telegram app and add the bot to your contact list. 5 | 6 | - First login with your matrix account: 7 | 8 | ``/login username password`` 9 | 10 | The bot will reply with information. 11 | - Use ``/join room_id_or_alias`` to join rooms, or ``/leave`` to leave them. 12 | - Once you have joined rooms, use ``/focus`` to choose what room you are interested at the moment. 13 | 14 | Focus 15 | ^^^^^ 16 | When communicating with our telegram bot, you only have one conversation windows open while you may have joined many matrix rooms. 17 | Showing all messages from all different rooms in one conversation is confusing and a big mess, hence the `focus` feature. 18 | 19 | If you send a message, the message will be relayed to your focused room only. 20 | When messages are being sent in your focused rooms, they will be relayed to your telegram client. Messages from other rooms you have joined will not be sent to you while not focused. 21 | 22 | Usage 23 | ***** 24 | To set your `focus` room simply write down ``/focus``, which will prompt you for the rooms you have joined. 25 | 26 | In order to view status regarding the rooms you have joined and focused room use the ``/status`` command. -------------------------------------------------------------------------------- /docs/commands.rst: -------------------------------------------------------------------------------- 1 | Bot commands 2 | ============ 3 | 4 | - ``/login `` 5 | 6 | Log in with your matrix username and password. 7 | - ``/logout`` 8 | 9 | Log out of your matrix user. 10 | - ``/join `` 11 | 12 | Join to the given room. 13 | - ``/leave`` 14 | 15 | Get a list of the rooms you have joined. 16 | - ``/discover_rooms`` 17 | 18 | Get a list of public rooms on the server. 19 | 20 | `This may not work on big servers with many public rooms` 21 | - ``/focus`` 22 | 23 | Interactive command. Prompt the user for the room he wants to "focus" right now. 24 | - ``/setname `` 25 | 26 | Sets matrix display name. 27 | - ``/status`` 28 | 29 | Return general information regarding the user status. 30 | - ``/create_room [invitees]`` 31 | 32 | Create a room with `room_alias` and invite `invitees` to it. 33 | Room alias should be provided without the homeserver suffix. 34 | Invitees is an optional space seperated list of matrix ids to be invited. 35 | 36 | - ``/me `` 37 | 38 | Send an emote to the room. 39 | 40 | Every other message (text, photos, videos) which is sent while logged in and focused to a room will be propagated to the room, and vice versa for the room messages being sent from other users. 41 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ![matrigram][logo]matrigram 2 | [![Build Status](https://travis-ci.org/GalPressman/matrigram.svg?branch=master)](https://travis-ci.org/GalPressman/matrigram) [![Documentation Status](https://readthedocs.org/projects/matrigram/badge/?version=latest)](http://matrigram.readthedocs.io/en/latest/?badge=latest) 3 | 4 | A bridge between *[matrix](https://www.matrix.org)* and *[telegram](https://www.telegram.org)*. 5 | 6 | ### Installation 7 | Clone the repository: 8 | ```bash 9 | $ git clone https://github.com/GalPressman/matrigram.git 10 | $ cd matrigram 11 | ``` 12 | Install dependencies using: 13 | ```bash 14 | $ pip install -r requirements.txt 15 | ``` 16 | 17 | ### Usage 18 | First fill `~/.matrigramconfig` with your details (similar to `config.json.example`). 19 | If the config file doesn't exist, matrigram will create one for you to fill. 20 | 21 | Run using `matrigram_main.py`, which will enter an infinite listening loop: 22 | ```python 23 | mg.message_loop(run_forever='-I- matrigram running...') 24 | ``` 25 | 26 | ### Documentation 27 | The documentation is hosted on [Read the Docs](http://matrigram.readthedocs.org). 28 | 29 | ### Comaptibility 30 | matrigram works on python2.7. 31 | 32 | We constantly update our [matrix-python-sdk](https://github.com/matrix-org/matrix-python-sdk) version, so 33 | requirements will _probably_ change frequently to keep up. 34 | 35 | [logo]: docs/logo.jpg "matrigram" 36 | -------------------------------------------------------------------------------- /matrigram_main.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import logging.handlers 3 | import os 4 | import sys 5 | import tempfile 6 | 7 | from matrigram import helper 8 | from matrigram.bot import MatrigramBot 9 | 10 | reload(sys) 11 | sys.setdefaultencoding('utf-8') 12 | 13 | 14 | def main(): 15 | logger = logging.getLogger('matrigram') 16 | logger.setLevel(logging.DEBUG) 17 | formatter = logging.Formatter(fmt='%(asctime)s %(levelname)s ' 18 | '%(module)s@%(funcName)s +%(lineno)d: %(message)s', 19 | datefmt='%H:%M:%S') 20 | sh = logging.StreamHandler() 21 | fh = logging.handlers.RotatingFileHandler('matrigram.log', maxBytes=10000, backupCount=1) 22 | sh.setFormatter(formatter) 23 | fh.setFormatter(formatter) 24 | logger.addHandler(sh) 25 | logger.addHandler(fh) 26 | 27 | if not os.path.isfile(helper.CONFIG_PATH): 28 | logger.error('Please fill the config file at %s', helper.CONFIG_PATH) 29 | helper.init_config() 30 | return 31 | 32 | config = helper.get_config() 33 | media_dir = os.path.join(tempfile.gettempdir(), "matrigram") 34 | if not os.path.exists(media_dir): 35 | logging.debug('creating dir %s', media_dir) 36 | os.mkdir(media_dir) 37 | 38 | config['media_dir'] = media_dir 39 | token = config['telegram_token'] 40 | if not helper.config_filled(): 41 | logger.error('Please enter you tg token in %s', helper.CONFIG_PATH) 42 | return 43 | 44 | mg = MatrigramBot(token, config=config) 45 | mg.message_loop(run_forever='-I- matrigram running...') 46 | 47 | 48 | if __name__ == '__main__': 49 | main() 50 | -------------------------------------------------------------------------------- /matrigram/helper.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import json 3 | import os 4 | import shutil 5 | 6 | import requests 7 | 8 | HELP_MSG = 'matrigram: A bridge between matrix and telegram' 9 | CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.matrigramconfig') 10 | 11 | 12 | def pprint_json(to_print): 13 | """Pretty print json. 14 | 15 | Args: 16 | to_print (json): The json to be printed. 17 | 18 | Returns: 19 | str: Pretty printed json string. 20 | """ 21 | return json.dumps(to_print, sort_keys=True, indent=4) 22 | 23 | 24 | def get_config(): 25 | """Query config file. 26 | 27 | Returns: 28 | dict: The config dictionary. 29 | """ 30 | with open(CONFIG_PATH) as config_file: 31 | return json.load(config_file) 32 | 33 | 34 | def download_file(url, path): 35 | """Download a file from the net. 36 | 37 | Args: 38 | url (str): Link to the file. 39 | path (str): Where to save. 40 | """ 41 | res = requests.get(url) 42 | with open(path, 'wb') as f: 43 | f.write(res.content) 44 | 45 | 46 | def list_to_nice_str(l): 47 | """Convert a string list to a ready to print string. 48 | 49 | Args: 50 | l (list): List of strings to be printed 51 | 52 | Returns: 53 | str: A string that can be printed. 54 | """ 55 | return ', '.join(l) 56 | 57 | 58 | def list_to_nice_lines(l): 59 | """Convert a string list to lines ready to printed. 60 | 61 | Args: 62 | l (list): List of strings to be printed 63 | 64 | Returns: 65 | str: A line separated string that can be printed. 66 | """ 67 | return '\n'.join(l) 68 | 69 | 70 | def chunks(l, n): 71 | """Yield successive n-sized chunks from l. 72 | 73 | Args: 74 | l (list): List to be split. 75 | n (int): Size of chunk. 76 | """ 77 | for i in range(0, len(l), n): 78 | yield l[i:i + n] 79 | 80 | 81 | def md5(fname): 82 | hash_md5 = hashlib.md5() 83 | with open(fname, 'rb') as f: 84 | for chunk in iter(lambda: f.read(4096), b''): 85 | hash_md5.update(chunk) 86 | return hash_md5.hexdigest() 87 | 88 | 89 | def init_config(): 90 | """Init ~/.matrigramconfig. 91 | 92 | """ 93 | shutil.copyfile('config.json.example', CONFIG_PATH) 94 | 95 | 96 | def config_filled(): 97 | """Check if the user filled the config file. 98 | 99 | Returns: 100 | bool: True if config is filled, else False. 101 | """ 102 | orig_md5 = md5('config.json.example') 103 | config_md5 = md5(CONFIG_PATH) 104 | 105 | return orig_md5 != config_md5 106 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # Internal variables. 11 | PAPEROPT_a4 = -D latex_paper_size=a4 12 | PAPEROPT_letter = -D latex_paper_size=letter 13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 14 | # the i18n builder cannot share the environment and doctrees with the others 15 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 16 | 17 | .PHONY: help 18 | help: 19 | @echo "Please use \`make ' where is one of" 20 | @echo " html to make standalone HTML files" 21 | @echo " dirhtml to make HTML files named index.html in directories" 22 | @echo " singlehtml to make a single large HTML file" 23 | @echo " pickle to make pickle files" 24 | @echo " json to make JSON files" 25 | @echo " htmlhelp to make HTML files and a HTML help project" 26 | @echo " qthelp to make HTML files and a qthelp project" 27 | @echo " applehelp to make an Apple Help Book" 28 | @echo " devhelp to make HTML files and a Devhelp project" 29 | @echo " epub to make an epub" 30 | @echo " epub3 to make an epub3" 31 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 32 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 33 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 34 | @echo " text to make text files" 35 | @echo " man to make manual pages" 36 | @echo " texinfo to make Texinfo files" 37 | @echo " info to make Texinfo files and run them through makeinfo" 38 | @echo " gettext to make PO message catalogs" 39 | @echo " changes to make an overview of all changed/added/deprecated items" 40 | @echo " xml to make Docutils-native XML files" 41 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 42 | @echo " linkcheck to check all external links for integrity" 43 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 44 | @echo " coverage to run coverage check of the documentation (if enabled)" 45 | @echo " dummy to check syntax errors of document sources" 46 | 47 | .PHONY: clean 48 | clean: 49 | rm -rf $(BUILDDIR)/* 50 | 51 | .PHONY: html 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | .PHONY: dirhtml 58 | dirhtml: 59 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 60 | @echo 61 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 62 | 63 | .PHONY: singlehtml 64 | singlehtml: 65 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 66 | @echo 67 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 68 | 69 | .PHONY: pickle 70 | pickle: 71 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 72 | @echo 73 | @echo "Build finished; now you can process the pickle files." 74 | 75 | .PHONY: json 76 | json: 77 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 78 | @echo 79 | @echo "Build finished; now you can process the JSON files." 80 | 81 | .PHONY: htmlhelp 82 | htmlhelp: 83 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 84 | @echo 85 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 86 | ".hhp project file in $(BUILDDIR)/htmlhelp." 87 | 88 | .PHONY: qthelp 89 | qthelp: 90 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 91 | @echo 92 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 93 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 94 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/matrigram.qhcp" 95 | @echo "To view the help file:" 96 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/matrigram.qhc" 97 | 98 | .PHONY: applehelp 99 | applehelp: 100 | $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp 101 | @echo 102 | @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." 103 | @echo "N.B. You won't be able to view it unless you put it in" \ 104 | "~/Library/Documentation/Help or install it in your application" \ 105 | "bundle." 106 | 107 | .PHONY: devhelp 108 | devhelp: 109 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 110 | @echo 111 | @echo "Build finished." 112 | @echo "To view the help file:" 113 | @echo "# mkdir -p $$HOME/.local/share/devhelp/matrigram" 114 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/matrigram" 115 | @echo "# devhelp" 116 | 117 | .PHONY: epub 118 | epub: 119 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 120 | @echo 121 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 122 | 123 | .PHONY: epub3 124 | epub3: 125 | $(SPHINXBUILD) -b epub3 $(ALLSPHINXOPTS) $(BUILDDIR)/epub3 126 | @echo 127 | @echo "Build finished. The epub3 file is in $(BUILDDIR)/epub3." 128 | 129 | .PHONY: latex 130 | latex: 131 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 132 | @echo 133 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 134 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 135 | "(use \`make latexpdf' here to do that automatically)." 136 | 137 | .PHONY: latexpdf 138 | latexpdf: 139 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 140 | @echo "Running LaTeX files through pdflatex..." 141 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 142 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 143 | 144 | .PHONY: latexpdfja 145 | latexpdfja: 146 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 147 | @echo "Running LaTeX files through platex and dvipdfmx..." 148 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 149 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 150 | 151 | .PHONY: text 152 | text: 153 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 154 | @echo 155 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 156 | 157 | .PHONY: man 158 | man: 159 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 160 | @echo 161 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 162 | 163 | .PHONY: texinfo 164 | texinfo: 165 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 166 | @echo 167 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 168 | @echo "Run \`make' in that directory to run these through makeinfo" \ 169 | "(use \`make info' here to do that automatically)." 170 | 171 | .PHONY: info 172 | info: 173 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 174 | @echo "Running Texinfo files through makeinfo..." 175 | make -C $(BUILDDIR)/texinfo info 176 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 177 | 178 | .PHONY: gettext 179 | gettext: 180 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 181 | @echo 182 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 183 | 184 | .PHONY: changes 185 | changes: 186 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 187 | @echo 188 | @echo "The overview file is in $(BUILDDIR)/changes." 189 | 190 | .PHONY: linkcheck 191 | linkcheck: 192 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 193 | @echo 194 | @echo "Link check complete; look for any errors in the above output " \ 195 | "or in $(BUILDDIR)/linkcheck/output.txt." 196 | 197 | .PHONY: doctest 198 | doctest: 199 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 200 | @echo "Testing of doctests in the sources finished, look at the " \ 201 | "results in $(BUILDDIR)/doctest/output.txt." 202 | 203 | .PHONY: coverage 204 | coverage: 205 | $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage 206 | @echo "Testing of coverage in the sources finished, look at the " \ 207 | "results in $(BUILDDIR)/coverage/python.txt." 208 | 209 | .PHONY: xml 210 | xml: 211 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 212 | @echo 213 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 214 | 215 | .PHONY: pseudoxml 216 | pseudoxml: 217 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 218 | @echo 219 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 220 | 221 | .PHONY: dummy 222 | dummy: 223 | $(SPHINXBUILD) -b dummy $(ALLSPHINXOPTS) $(BUILDDIR)/dummy 224 | @echo 225 | @echo "Build finished. Dummy builder generates no files." 226 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # matrigram documentation build configuration file, created by 4 | # sphinx-quickstart on Tue Dec 20 11:09:38 2016. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | # If extensions (or modules to document with autodoc) are in another directory, 16 | # add these directories to sys.path here. If the directory is relative to the 17 | # documentation root, use os.path.abspath to make it absolute, like shown here. 18 | # 19 | import os 20 | import sys 21 | sys.path.insert(0, os.path.abspath('../matrigram')) 22 | sys.path.insert(0, os.path.abspath('../')) 23 | 24 | # -- General configuration ------------------------------------------------ 25 | 26 | # If your documentation needs a minimal Sphinx version, state it here. 27 | # 28 | # needs_sphinx = '1.0' 29 | 30 | # Add any Sphinx extension module names here, as strings. They can be 31 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 32 | # ones. 33 | extensions = [ 34 | 'sphinx.ext.autodoc', 35 | 'sphinx.ext.doctest', 36 | 'sphinx.ext.intersphinx', 37 | 'sphinx.ext.todo', 38 | 'sphinx.ext.viewcode', 39 | 'sphinx.ext.napoleon', 40 | ] 41 | 42 | # Add any paths that contain templates here, relative to this directory. 43 | templates_path = ['_templates'] 44 | 45 | # The suffix(es) of source filenames. 46 | # You can specify multiple suffix as a list of string: 47 | # 48 | # source_suffix = ['.rst', '.md'] 49 | source_suffix = '.rst' 50 | 51 | # The encoding of source files. 52 | # 53 | # source_encoding = 'utf-8-sig' 54 | 55 | # The master toctree document. 56 | master_doc = 'index' 57 | 58 | # General information about the project. 59 | project = u'matrigram' 60 | copyright = u'2016, Gal Pressman & Yuval Fatael' 61 | author = u'Gal Pressman & Yuval Fatael' 62 | 63 | # The version info for the project you're documenting, acts as replacement for 64 | # |version| and |release|, also used in various other places throughout the 65 | # built documents. 66 | # 67 | # The short X.Y version. 68 | version = u'0.0.1' 69 | # The full version, including alpha/beta/rc tags. 70 | release = u'0.0.1' 71 | 72 | # The language for content autogenerated by Sphinx. Refer to documentation 73 | # for a list of supported languages. 74 | # 75 | # This is also used if you do content translation via gettext catalogs. 76 | # Usually you set "language" from the command line for these cases. 77 | language = None 78 | 79 | # There are two options for replacing |today|: either, you set today to some 80 | # non-false value, then it is used: 81 | # 82 | # today = '' 83 | # 84 | # Else, today_fmt is used as the format for a strftime call. 85 | # 86 | # today_fmt = '%B %d, %Y' 87 | 88 | # List of patterns, relative to source directory, that match files and 89 | # directories to ignore when looking for source files. 90 | # This patterns also effect to html_static_path and html_extra_path 91 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] 92 | 93 | # The reST default role (used for this markup: `text`) to use for all 94 | # documents. 95 | # 96 | # default_role = None 97 | 98 | # If true, '()' will be appended to :func: etc. cross-reference text. 99 | # 100 | # add_function_parentheses = True 101 | 102 | # If true, the current module name will be prepended to all description 103 | # unit titles (such as .. function::). 104 | # 105 | # add_module_names = True 106 | 107 | # If true, sectionauthor and moduleauthor directives will be shown in the 108 | # output. They are ignored by default. 109 | # 110 | # show_authors = False 111 | 112 | # The name of the Pygments (syntax highlighting) style to use. 113 | pygments_style = 'sphinx' 114 | 115 | # A list of ignored prefixes for module index sorting. 116 | # modindex_common_prefix = [] 117 | 118 | # If true, keep warnings as "system message" paragraphs in the built documents. 119 | # keep_warnings = False 120 | 121 | # If true, `todo` and `todoList` produce output, else they produce nothing. 122 | todo_include_todos = True 123 | 124 | 125 | # -- Options for HTML output ---------------------------------------------- 126 | 127 | # The theme to use for HTML and HTML Help pages. See the documentation for 128 | # a list of builtin themes. 129 | # 130 | html_theme = 'alabaster' 131 | 132 | # Theme options are theme-specific and customize the look and feel of a theme 133 | # further. For a list of options available for each theme, see the 134 | # documentation. 135 | # 136 | html_theme_options = { 137 | 'github_user': 'GalPressman', 138 | 'github_repo': 'matrigram', 139 | 'github_banner': True, 140 | 'github_button': True, 141 | 'travis_button': True, 142 | 'show_powered_by': False, 143 | } 144 | 145 | # Add any paths that contain custom themes here, relative to this directory. 146 | # html_theme_path = [] 147 | 148 | # The name for this set of Sphinx documents. 149 | # " v documentation" by default. 150 | # 151 | # html_title = u'matrigram v0.0.1' 152 | 153 | # A shorter title for the navigation bar. Default is the same as html_title. 154 | # 155 | # html_short_title = None 156 | 157 | # The name of an image file (relative to this directory) to place at the top 158 | # of the sidebar. 159 | # 160 | html_logo = 'logo.jpg' 161 | 162 | # The name of an image file (relative to this directory) to use as a favicon of 163 | # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 164 | # pixels large. 165 | # 166 | # html_favicon = None 167 | 168 | # Add any paths that contain custom static files (such as style sheets) here, 169 | # relative to this directory. They are copied after the builtin static files, 170 | # so a file named "default.css" will overwrite the builtin "default.css". 171 | html_static_path = ['_static'] 172 | 173 | # Add any extra paths that contain custom files (such as robots.txt or 174 | # .htaccess) here, relative to this directory. These files are copied 175 | # directly to the root of the documentation. 176 | # 177 | # html_extra_path = [] 178 | 179 | # If not None, a 'Last updated on:' timestamp is inserted at every page 180 | # bottom, using the given strftime format. 181 | # The empty string is equivalent to '%b %d, %Y'. 182 | # 183 | # html_last_updated_fmt = None 184 | 185 | # If true, SmartyPants will be used to convert quotes and dashes to 186 | # typographically correct entities. 187 | # 188 | # html_use_smartypants = True 189 | 190 | # Custom sidebar templates, maps document names to template names. 191 | # 192 | html_sidebars = { 193 | '**': [ 194 | 'about.html', 195 | 'badges.html', 196 | 'navigation.html', 197 | 'searchbox.html', 198 | ] 199 | } 200 | 201 | # Additional templates that should be rendered to pages, maps page names to 202 | # template names. 203 | # 204 | # html_additional_pages = {} 205 | 206 | # If false, no module index is generated. 207 | # 208 | # html_domain_indices = True 209 | 210 | # If false, no index is generated. 211 | # 212 | # html_use_index = True 213 | 214 | # If true, the index is split into individual pages for each letter. 215 | # 216 | # html_split_index = False 217 | 218 | # If true, links to the reST sources are added to the pages. 219 | # 220 | # html_show_sourcelink = True 221 | 222 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 223 | # 224 | # html_show_sphinx = True 225 | 226 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 227 | # 228 | # html_show_copyright = True 229 | 230 | # If true, an OpenSearch description file will be output, and all pages will 231 | # contain a tag referring to it. The value of this option must be the 232 | # base URL from which the finished HTML is served. 233 | # 234 | # html_use_opensearch = '' 235 | 236 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 237 | # html_file_suffix = None 238 | 239 | # Language to be used for generating the HTML full-text search index. 240 | # Sphinx supports the following languages: 241 | # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' 242 | # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh' 243 | # 244 | # html_search_language = 'en' 245 | 246 | # A dictionary with options for the search language support, empty by default. 247 | # 'ja' uses this config value. 248 | # 'zh' user can custom change `jieba` dictionary path. 249 | # 250 | # html_search_options = {'type': 'default'} 251 | 252 | # The name of a javascript file (relative to the configuration directory) that 253 | # implements a search results scorer. If empty, the default will be used. 254 | # 255 | # html_search_scorer = 'scorer.js' 256 | 257 | # Output file base name for HTML help builder. 258 | htmlhelp_basename = 'matrigramdoc' 259 | 260 | # -- Options for LaTeX output --------------------------------------------- 261 | 262 | latex_elements = { 263 | # The paper size ('letterpaper' or 'a4paper'). 264 | # 265 | # 'papersize': 'letterpaper', 266 | 267 | # The font size ('10pt', '11pt' or '12pt'). 268 | # 269 | # 'pointsize': '10pt', 270 | 271 | # Additional stuff for the LaTeX preamble. 272 | # 273 | # 'preamble': '', 274 | 275 | # Latex figure (float) alignment 276 | # 277 | # 'figure_align': 'htbp', 278 | } 279 | 280 | # Grouping the document tree into LaTeX files. List of tuples 281 | # (source start file, target name, title, 282 | # author, documentclass [howto, manual, or own class]). 283 | latex_documents = [ 284 | (master_doc, 'matrigram.tex', u'matrigram Documentation', 285 | u'Gal Pressman \\& Yuval Fatael', 'manual'), 286 | ] 287 | 288 | # The name of an image file (relative to this directory) to place at the top of 289 | # the title page. 290 | # 291 | # latex_logo = None 292 | 293 | # For "manual" documents, if this is true, then toplevel headings are parts, 294 | # not chapters. 295 | # 296 | # latex_use_parts = False 297 | 298 | # If true, show page references after internal links. 299 | # 300 | # latex_show_pagerefs = False 301 | 302 | # If true, show URL addresses after external links. 303 | # 304 | # latex_show_urls = False 305 | 306 | # Documents to append as an appendix to all manuals. 307 | # 308 | # latex_appendices = [] 309 | 310 | # It false, will not define \strong, \code, itleref, \crossref ... but only 311 | # \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added 312 | # packages. 313 | # 314 | # latex_keep_old_macro_names = True 315 | 316 | # If false, no module index is generated. 317 | # 318 | # latex_domain_indices = True 319 | 320 | 321 | # -- Options for manual page output --------------------------------------- 322 | 323 | # One entry per manual page. List of tuples 324 | # (source start file, name, description, authors, manual section). 325 | man_pages = [ 326 | (master_doc, 'matrigram', u'matrigram Documentation', 327 | [author], 1) 328 | ] 329 | 330 | # If true, show URL addresses after external links. 331 | # 332 | # man_show_urls = False 333 | 334 | 335 | # -- Options for Texinfo output ------------------------------------------- 336 | 337 | # Grouping the document tree into Texinfo files. List of tuples 338 | # (source start file, target name, title, author, 339 | # dir menu entry, description, category) 340 | texinfo_documents = [ 341 | (master_doc, 'matrigram', u'matrigram Documentation', 342 | author, 'matrigram', 'One line description of project.', 343 | 'Miscellaneous'), 344 | ] 345 | 346 | # Documents to append as an appendix to all manuals. 347 | # 348 | # texinfo_appendices = [] 349 | 350 | # If false, no module index is generated. 351 | # 352 | # texinfo_domain_indices = True 353 | 354 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 355 | # 356 | # texinfo_show_urls = 'footnote' 357 | 358 | # If true, do not generate a @detailmenu in the "Top" node's menu. 359 | # 360 | # texinfo_no_detailmenu = False 361 | 362 | 363 | # Example configuration for intersphinx: refer to the Python standard library. 364 | intersphinx_mapping = {'https://docs.python.org/': None} 365 | -------------------------------------------------------------------------------- /matrigram/client.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import logging 4 | import mimetypes 5 | import os 6 | 7 | import requests 8 | from matrix_client.client import MatrixClient 9 | from matrix_client.client import MatrixRequestError 10 | from requests import ConnectionError 11 | 12 | from .helper import download_file 13 | from .helper import pprint_json 14 | 15 | logger = logging.getLogger('matrigram') 16 | 17 | 18 | class MatrigramClient(object): 19 | def __init__(self, server, tb, username): 20 | self.client = MatrixClient(server) 21 | self.tb = tb 22 | self.token = None 23 | self.server = server 24 | self.username = username 25 | self.focus_room_id = None 26 | self.msg_type_router = { 27 | 'm.image': self.forward_image_to_tb, 28 | 'm.audio': self.forward_voice_to_tb, 29 | 'm.video': self.forward_video_to_tb, 30 | 'm.emote': self.forward_emote_to_tb, 31 | } 32 | self.room_listener_uid = None 33 | self.ephemeral_listener_uid = None 34 | 35 | def login(self, username, password): 36 | try: 37 | self.token = self.client.login_with_password(username, password) 38 | logger.info('token = %s', self.token) 39 | rooms = self.get_rooms_aliases() 40 | if rooms: 41 | # set focus room to "first" room 42 | self.set_focus_room(rooms.keys()[0]) 43 | 44 | self.client.add_invite_listener(self.on_invite_event) 45 | self.client.add_leave_listener(self.on_leave_event) 46 | self.client.start_listener_thread() 47 | return True, "OK" 48 | except MatrixRequestError: 49 | return False, "Failed to login" 50 | except ConnectionError: 51 | return False, "Server is offline" 52 | 53 | def logout(self): 54 | self.client.logout() 55 | 56 | def on_event(self, _, event): 57 | logger.debug('entered with message %s', pprint_json(event)) 58 | sender = event['sender'].split(':')[0].encode('utf-8') 59 | 60 | # Prevent messages loopback 61 | if sender.startswith(u'@{}'.format(self.username)): 62 | return 63 | 64 | if event['type'] == "m.room.message": 65 | msgtype = event['content']['msgtype'] 66 | 67 | if msgtype != 'm.text': 68 | callback = self.msg_type_router.get(msgtype) 69 | if callback: 70 | callback(event) 71 | return 72 | 73 | content = event['content']['body'].encode('utf-8') 74 | self.tb.send_message(sender, content, self) 75 | 76 | elif event['type'] == "m.room.topic": 77 | topic = event['content']['topic'].encode('utf-8') 78 | self.tb.send_topic(sender, topic, self) 79 | 80 | def on_ephemeral_event(self, _, ee): 81 | logger.debug(pprint_json(ee)) 82 | 83 | if ee['type'] == 'm.typing': 84 | if ee['content']['user_ids']: 85 | self.tb.start_typing_thread(self) 86 | else: 87 | self.tb.stop_typing_thread(self) 88 | 89 | def on_leave_event(self, room_id, le): 90 | logger.debug(pprint_json(le)) 91 | 92 | if le['timeline']['events'][0]['sender'] != le['timeline']['events'][0]['state_key']: 93 | self.tb.send_kick(self._room_id_to_alias(room_id), self) 94 | 95 | def on_invite_event(self, _, ie): 96 | logger.debug('invite event %s', pprint_json(ie)) 97 | room_name = None 98 | for event in ie['events']: 99 | if event['type'] == 'm.room.name': 100 | room_name = event['content']['name'] 101 | 102 | if room_name: 103 | self.tb.send_invite(self, self._room_id_to_alias(room_name)) 104 | 105 | def join_room(self, room_id_or_alias): 106 | try: 107 | self.client.join_room(room_id_or_alias) 108 | self.set_focus_room(room_id_or_alias) 109 | return True 110 | except MatrixRequestError: 111 | return False 112 | 113 | def leave_room(self, room_id_or_alias): 114 | room = self.get_room_obj(room_id_or_alias) 115 | if not room: 116 | logger.error('cant find room') 117 | return False 118 | 119 | if self.focus_room_id == room.room_id: 120 | rooms = self.get_rooms_aliases() 121 | room_id = self._room_alias_to_id(room_id_or_alias) 122 | 123 | del rooms[room_id] 124 | new_focus_room = rooms.keys()[0] if rooms else None 125 | self.set_focus_room(new_focus_room) 126 | 127 | return room.leave() 128 | 129 | def set_focus_room(self, room_id_or_alias): 130 | if self._room_alias_to_id(room_id_or_alias) == self.focus_room_id: 131 | return 132 | 133 | # remove current focus room listeners 134 | if self.focus_room_id is not None: 135 | room_obj = self.get_room_obj(self.focus_room_id) 136 | room_obj.remove_listener(self.room_listener_uid) 137 | self.room_listener_uid = None 138 | room_obj.remove_ephemeral_listener(self.ephemeral_listener_uid) 139 | self.ephemeral_listener_uid = None 140 | logger.info("remove focus room %s", self.focus_room_id) 141 | self.focus_room_id = None 142 | 143 | # set new room on focus 144 | if room_id_or_alias is not None: 145 | self.focus_room_id = self._room_alias_to_id(room_id_or_alias) 146 | room_obj = self.get_room_obj(self.focus_room_id) 147 | self.room_listener_uid = room_obj.add_listener(self.on_event) 148 | self.ephemeral_listener_uid = room_obj.add_ephemeral_listener(self.on_ephemeral_event) 149 | logger.info("set focus room to %s", self.focus_room_id) 150 | 151 | def get_focus_room_alias(self): 152 | return self._room_id_to_alias(self.focus_room_id) 153 | 154 | def have_focus_room(self): 155 | return self.focus_room_id is not None 156 | 157 | def get_members(self): 158 | room_obj = self.get_room_obj(self.focus_room_id) 159 | rtn = room_obj.get_joined_members() 160 | 161 | return [member['displayname'] for _, member in rtn.items() if member.get('displayname')] 162 | 163 | def set_name(self, name): 164 | user = self.client.get_user(self.client.user_id) 165 | user.set_display_name(name) 166 | 167 | def emote(self, body): 168 | room_obj = self.get_room_obj(self.focus_room_id) 169 | room_obj.send_emote(body) 170 | 171 | def create_room(self, alias, is_public=False, invitees=()): 172 | try: 173 | room_obj = self.client.create_room(alias, is_public, invitees) 174 | room_obj.update_aliases() 175 | logger.debug('room_id %s', room_obj.room_id) 176 | logger.debug('room_alias %s', room_obj.aliases[0]) 177 | return (room_obj.room_id, room_obj.aliases[0]) 178 | except MatrixRequestError: 179 | logger.error('error creating room') 180 | return None, None 181 | 182 | def backfill_previous_messages(self, limit=10): 183 | room_obj = self.get_room_obj(self.focus_room_id) 184 | room_obj.backfill_previous_messages(limit=limit) 185 | 186 | def get_rooms_aliases(self): 187 | # returns a dict with id: room obj 188 | rooms = self._get_rooms_updated() 189 | if not rooms: 190 | return rooms 191 | 192 | logger.debug("rooms got from server are %s", rooms) 193 | 194 | # return dict with id: list of aliases or id (if no alias exists) 195 | return {key: val.aliases if val.aliases else [key] for (key, val) in rooms.items()} 196 | 197 | def get_room_obj(self, room_id_or_alias): 198 | """Get room object of specific id or alias. 199 | 200 | Args: 201 | room_id_or_alias (str): Room's id or alias. 202 | 203 | Returns (Room): Room object corresponding to room_id_or_alias. 204 | 205 | """ 206 | rooms = self._get_rooms_updated() 207 | room_id = self._room_alias_to_id(room_id_or_alias) 208 | 209 | return rooms.get(room_id) 210 | 211 | def send_message(self, msg): 212 | room_obj = self.get_room_obj(self.focus_room_id) 213 | 214 | if not room_obj: 215 | logger.error('cant find room') 216 | else: 217 | room_obj.send_text(msg) 218 | 219 | def send_photo(self, path): 220 | with open(path, 'rb') as f: 221 | mxcurl = self.client.upload(f.read(), mimetypes.guess_type(path)[0]) 222 | 223 | room_obj = self.get_room_obj(self.focus_room_id) 224 | 225 | if not room_obj: 226 | logger.error('cant find room') 227 | else: 228 | room_obj.send_image(mxcurl, os.path.split(path)[1]) 229 | 230 | def send_voice(self, path): 231 | with open(path, 'rb') as f: 232 | mxcurl = self.client.upload(f.read(), mimetypes.guess_type(path)[0]) 233 | room_obj = self.get_room_obj(self.focus_room_id) 234 | room_obj.send_audio(mxcurl, os.path.split(path)[1]) 235 | 236 | def send_video(self, path): 237 | with open(path, 'rb') as f: 238 | mxcurl = self.client.upload(f.read(), mimetypes.guess_type(path)[0]) 239 | room_obj = self.get_room_obj(self.focus_room_id) 240 | room_obj.send_video(mxcurl, os.path.split(path)[1]) 241 | 242 | def discover_rooms(self): 243 | res = requests.get('{}/_matrix/client/r0/publicRooms?limit=20'.format(self.server)) 244 | res_json = res.json() 245 | 246 | room_objs = res_json['chunk'] 247 | return [room['aliases'][0] for room in room_objs if room.get('aliases')] 248 | 249 | def download_from_event(self, event): 250 | mxcurl = event['content']['url'] 251 | link = self.client.api.get_download_url(mxcurl) 252 | media_id = mxcurl.split('/')[3] 253 | media_type = event['content']['info']['mimetype'].split('/')[1] 254 | path = os.path.join(self.tb.config['media_dir'], '{}.{}'.format(media_id, media_type)) 255 | download_file(link, path) 256 | 257 | return path 258 | 259 | def forward_image_to_tb(self, event): 260 | sender = event['sender'].split(':')[0].encode('utf-8') 261 | path = self.download_from_event(event) 262 | self.tb.send_photo(sender, path, self) 263 | 264 | def forward_voice_to_tb(self, event): 265 | sender = event['sender'].split(':')[0].encode('utf-8') 266 | path = self.download_from_event(event) 267 | self.tb.send_voice(sender, path, self) 268 | 269 | def forward_video_to_tb(self, event): 270 | sender = event['sender'].split(':')[0].encode('utf-8') 271 | path = self.download_from_event(event) 272 | self.tb.send_video(sender, path, self) 273 | 274 | def forward_emote_to_tb(self, event): 275 | sender = event['sender'].split(':')[0].encode('utf-8') 276 | content = event['content']['body'].encode('utf-8') 277 | self.tb.send_emote(sender, content, self) 278 | 279 | def _room_id_to_alias(self, id): 280 | """Convert room id to alias. 281 | 282 | Args: 283 | id (str): Room id. 284 | 285 | Returns (str): Room alias. 286 | 287 | """ 288 | if id is None: 289 | return None 290 | if id.startswith('#'): 291 | return id 292 | rooms = self.get_rooms_aliases() 293 | if id in rooms: 294 | return rooms[id][0] 295 | else: 296 | return None 297 | 298 | def _room_alias_to_id(self, alias): 299 | """Convert room alias to id. 300 | 301 | Args: 302 | alias (str): Room alias. 303 | 304 | Returns (str): Room id. 305 | 306 | """ 307 | if alias is None: 308 | return None 309 | 310 | if not alias.startswith('#'): 311 | return alias 312 | 313 | return self.client.api.get_room_id(alias) 314 | 315 | def _get_rooms_updated(self): 316 | """Return rooms dictionary with updated aliases. 317 | 318 | Returns (dict): Return rooms dictionary with updated aliases. 319 | 320 | """ 321 | rooms = self.client.get_rooms() 322 | for room in rooms.values(): 323 | room.update_aliases() 324 | 325 | return rooms 326 | -------------------------------------------------------------------------------- /matrigram/bot.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import logging 4 | import os 5 | import re 6 | import time 7 | from threading import Lock 8 | from threading import Thread 9 | 10 | import requests 11 | import telepot 12 | 13 | from . import helper 14 | from .helper import download_file 15 | from .helper import pprint_json 16 | from .client import MatrigramClient 17 | 18 | BOT_BASE_URL = 'https://api.telegram.org/bot{token}/{path}' 19 | BOT_FILE_URL = 'https://api.telegram.org/file/bot{token}/{file_path}' 20 | logger = logging.getLogger('matrigram') 21 | 22 | OPTS_IN_ROW = 4 23 | 24 | 25 | def logged_in(func): 26 | def func_wrapper(self, msg, *args): 27 | chat_id = msg['chat']['id'] 28 | client = self._get_client(chat_id) 29 | if client is None: 30 | self.sendMessage(chat_id, 31 | 'You are not logged in. Login to start with /login username password') 32 | return 33 | func(self, msg, *args) 34 | 35 | return func_wrapper 36 | 37 | 38 | def focused(func): 39 | def func_wrapper(self, msg, *args): 40 | chat_id = msg['chat']['id'] 41 | client = self._get_client(chat_id) 42 | if not client.get_rooms_aliases(): 43 | self.sendMessage(chat_id, 'You are not in any room. Type /join #room to join one.') 44 | return 45 | if not client.have_focus_room(): 46 | self.sendMessage(chat_id, 'You don\'t have a room in focus. Type /focus to choose one.') 47 | return 48 | func(self, msg, *args) 49 | 50 | return func_wrapper 51 | 52 | 53 | class MatrigramBot(telepot.Bot): 54 | def __init__(self, *args, **kwargs): 55 | config = kwargs.pop('config') 56 | 57 | super(MatrigramBot, self).__init__(*args, **kwargs) 58 | 59 | routes = [ 60 | (r'^/login (?P\S+) (?P\S+)$', self.login), 61 | (r'^/logout$', self.logout), 62 | (r'^/join\s(?P[^$]+)$', self.join_room), 63 | (r'^/leave$', self.leave_room), 64 | (r'^/discover$', self.discover_rooms), 65 | (r'^/focus$', self.change_focus_room), 66 | (r'^/status$', self.status), 67 | (r'^/members$', self.get_members), 68 | (r'^/create_room (?P[\S]+)(?P\s.*\S)*$', self.create_room), 69 | (r'^/setname\s(?P[^$]+)$', self.set_name), 70 | (r'^/me (?P[^/].*)$', self.emote), 71 | (r'^(?P[^/].*)$', self.forward_message_to_mc), 72 | ] 73 | 74 | callback_query_routes = [ 75 | (r'^LEAVE (?P\S+)$', self.do_leave), 76 | (r'^FOCUS (?P\S+)$', self.do_change_focus), 77 | (r'^JOIN (?P\S+)$', self.do_join), 78 | (r'^NOP$', self.do_nop), 79 | ] 80 | 81 | self.routes = [(re.compile(pattern), callback) for pattern, callback in routes] 82 | self.callback_query_routes = [(re.compile(pattern), callback) 83 | for pattern, callback in callback_query_routes] 84 | 85 | self.content_type_routes = { 86 | 'text': self.on_text_message, 87 | 'photo': self.forward_photo_to_mc, 88 | 'voice': self.forward_voice_to_mc, 89 | 'video': self.forward_video_to_mc, 90 | 'document': self.forward_gif_to_mc, 91 | } 92 | 93 | # users map telegram_id -> client 94 | self.users = {} 95 | self.config = config 96 | 97 | self.users_lock = Lock() # self.users lock for typing related matters 98 | 99 | def on_chat_message(self, msg): 100 | """Main entry point. 101 | 102 | This function is our main entry point to the bot. 103 | Messages will be routed according to their content type. 104 | 105 | Args: 106 | msg: The message object received from telegram user. 107 | """ 108 | content_type, _, _ = telepot.glance(msg) 109 | logger.debug('content type: %s', content_type) 110 | self.content_type_routes[content_type](msg) 111 | 112 | def on_callback_query(self, msg): 113 | """Handle callback queries. 114 | 115 | Route queries using ``self.callback_query_routes``. 116 | 117 | Args: 118 | msg: The message object received from telegram user. 119 | """ 120 | data = msg['data'] 121 | 122 | for route, callback in self.callback_query_routes: 123 | match = route.match(data) 124 | if match: 125 | callback_thread = Thread(target=callback, args=(msg, match)) 126 | callback_thread.start() 127 | break 128 | 129 | def on_text_message(self, msg): 130 | """Handle text messages. 131 | 132 | Route text messages using ``self.routes``. 133 | 134 | Args: 135 | msg: The message object received from telegram user. 136 | """ 137 | text = msg['text'].encode('utf-8') 138 | 139 | for route, callback in self.routes: 140 | match = route.match(text) 141 | if match: 142 | callback_thread = Thread(target=callback, args=(msg, match)) 143 | callback_thread.start() 144 | 145 | # wait for login thread to finish before moving on 146 | if callback == self.login: 147 | callback_thread.join() 148 | break 149 | 150 | def login(self, msg, match): 151 | """Perform login. 152 | 153 | Args: 154 | msg: The message object received from telegram user. 155 | match: Match object containing extracted data. 156 | """ 157 | username = match.group('username') 158 | password = match.group('password') 159 | chat_id = msg['chat']['id'] 160 | 161 | logger.info('telegram user %s, login to %s', chat_id, username) 162 | self.sendChatAction(chat_id, 'typing') 163 | 164 | client = MatrigramClient(self.config['server'], self, username) 165 | login_bool, login_message = client.login(username, password) 166 | if login_bool: 167 | self.sendMessage(chat_id, 'Logged in as {}'.format(username)) 168 | 169 | self.users[chat_id] = { 170 | 'client': client, 171 | 'typing_thread': None, 172 | 'should_type': False, 173 | } 174 | 175 | rooms = client.get_rooms_aliases() 176 | logger.debug("rooms are: %s", rooms) 177 | 178 | if rooms: 179 | room_aliases = '\n'.join([room_alias[0] for room_alias in rooms.values()]) 180 | self.sendMessage(chat_id, 'You are currently in rooms:\n{}'.format(room_aliases)) 181 | self.sendMessage(chat_id, 182 | 'You are now participating in: {}'.format( 183 | client.get_focus_room_alias())) 184 | logger.debug('%s user state:\n%s', chat_id, self.users[chat_id]) 185 | else: 186 | self.sendMessage(chat_id, login_message) 187 | 188 | @logged_in 189 | def logout(self, msg, _): 190 | """Perform logout. 191 | 192 | Args: 193 | msg: The message object received from telegram user. 194 | """ 195 | chat_id = msg['chat']['id'] 196 | client = self._get_client(chat_id) 197 | 198 | logger.info('logout %s', chat_id) 199 | 200 | client.logout() 201 | self.users[chat_id]['client'] = None 202 | 203 | @logged_in 204 | def join_room(self, msg, match): 205 | chat_id = msg['chat']['id'] 206 | client = self._get_client(chat_id) 207 | room_name = match.group('room_name') 208 | ret = client.join_room(room_name) 209 | if not ret: 210 | self.sendMessage(chat_id, 'Can\'t join room') 211 | else: 212 | self.sendMessage(chat_id, "Joined {}".format(room_name)) 213 | 214 | @logged_in 215 | def leave_room(self, msg, _): 216 | chat_id = msg['chat']['id'] 217 | client = self._get_client(chat_id) 218 | 219 | rooms = [room[0] for dummy_room_id, room in client.get_rooms_aliases().items()] 220 | if not rooms: 221 | self.sendMessage(chat_id, 'Nothing to leave...') 222 | return 223 | 224 | opts = [{'text': room, 'callback_data': 'LEAVE {}'.format(room)} for room in rooms] 225 | 226 | keyboard = { 227 | 'inline_keyboard': [chunk for chunk in helper.chunks(opts, OPTS_IN_ROW)] 228 | } 229 | self.sendMessage(chat_id, 'Choose a room to leave:', reply_markup=keyboard) 230 | 231 | def do_leave(self, msg, match): 232 | query_id, _, _ = telepot.glance(msg, flavor='callback_query') 233 | chat_id = msg['message']['chat']['id'] 234 | room_name = match.group('room') 235 | client = self._get_client(chat_id) 236 | 237 | prev_focus_room = client.get_focus_room_alias() 238 | client.leave_room(room_name) 239 | self.sendMessage(chat_id, 'Left {}'.format(room_name)) 240 | curr_focus_room = client.get_focus_room_alias() 241 | 242 | if curr_focus_room != prev_focus_room and curr_focus_room is not None: 243 | self.sendMessage(chat_id, 244 | 'You are now participating in: {}'.format( 245 | client.get_focus_room_alias())) 246 | 247 | self.answerCallbackQuery(query_id, 'Done!') 248 | 249 | @logged_in 250 | def change_focus_room(self, msg, _): 251 | chat_id = msg['chat']['id'] 252 | client = self._get_client(chat_id) 253 | 254 | rooms = [room[0] for dummy_room_id, room in client.get_rooms_aliases().items()] 255 | if not rooms or len(rooms) == 0: 256 | self.sendMessage(chat_id, 'You need to be at least in one room to use this command.') 257 | return 258 | 259 | opts = [{'text': room, 'callback_data': 'FOCUS {}'.format(room)} for room in rooms] 260 | 261 | keyboard = { 262 | 'inline_keyboard': [chunk for chunk in helper.chunks(opts, OPTS_IN_ROW)] 263 | } 264 | self.sendMessage(chat_id, 'Choose a room to focus:', reply_markup=keyboard) 265 | 266 | def do_change_focus(self, msg, match): 267 | query_id, _, _ = telepot.glance(msg, flavor='callback_query') 268 | chat_id = msg['message']['chat']['id'] 269 | room_name = match.group('room') 270 | 271 | self.sendChatAction(chat_id, 'typing') 272 | client = self._get_client(chat_id) 273 | 274 | client.set_focus_room(room_name) 275 | self.sendMessage(chat_id, 'You are now participating in {}'.format(room_name)) 276 | self.sendMessage(chat_id, '{} Room history:'.format(room_name)) 277 | client.backfill_previous_messages() 278 | 279 | self.answerCallbackQuery(query_id, 'Done!') 280 | 281 | def do_join(self, msg, match): 282 | query_id, _, _ = telepot.glance(msg, flavor='callback_query') 283 | chat_id = msg['message']['chat']['id'] 284 | room_name = match.group('room') 285 | 286 | self.sendChatAction(chat_id, 'typing') 287 | client = self._get_client(chat_id) 288 | 289 | ret = client.join_room(room_name) 290 | if not ret: 291 | self.answerCallbackQuery(query_id, 'Can\'t join room') 292 | else: 293 | self.answerCallbackQuery(query_id, 'Joined {}'.format(room_name)) 294 | 295 | def do_nop(self, msg, _): 296 | query_id, _, _ = telepot.glance(msg, flavor='callback_query') 297 | chat_id = msg['message']['chat']['id'] 298 | 299 | self.sendChatAction(chat_id, 'typing') 300 | self.answerCallbackQuery(query_id, 'OK Boss!') 301 | 302 | @logged_in 303 | def status(self, msg, _): 304 | chat_id = msg['chat']['id'] 305 | self.sendChatAction(chat_id, 'typing') 306 | client = self._get_client(chat_id) 307 | 308 | focus_room = client.get_focus_room_alias() 309 | joined_rooms = client.get_rooms_aliases() 310 | joined_rooms_list = [val[0] for dummy_room_id, val in joined_rooms.items()] 311 | 312 | message = '''Status: 313 | Focused room: {} 314 | Joined rooms: {}'''.format(focus_room, helper.list_to_nice_str(joined_rooms_list)) 315 | self.sendMessage(chat_id, message) 316 | 317 | @logged_in 318 | @focused 319 | def get_members(self, msg, _): 320 | chat_id = msg['chat']['id'] 321 | client = self._get_client(chat_id) 322 | 323 | l = client.get_members() 324 | # TODO: we need to think how we avoid too long messages, for now send 10 elements 325 | self.sendMessage(chat_id, helper.list_to_nice_str(l[0:10])) 326 | 327 | @logged_in 328 | def discover_rooms(self, msg, _): 329 | chat_id = msg['chat']['id'] 330 | client = self._get_client(chat_id) 331 | 332 | rooms = client.discover_rooms() 333 | self.sendMessage(chat_id, helper.list_to_nice_lines(rooms)) 334 | 335 | @logged_in 336 | def create_room(self, msg, match): 337 | chat_id = msg['chat']['id'] 338 | client = self._get_client(chat_id) 339 | room_alias = match.group('room_name') 340 | invitees = match.group('invitees') 341 | 342 | invitees = invitees.split() if invitees else None 343 | room_id, actual_alias = client.create_room(room_alias, is_public=True, invitees=invitees) 344 | if room_id: 345 | self.sendMessage(chat_id, 346 | 'Created room {} with room id {}'.format(actual_alias, room_id)) 347 | self.sendMessage(chat_id, 348 | 'Invitees for the rooms are {}'.format( 349 | helper.list_to_nice_str(invitees))) 350 | else: 351 | self.sendMessage(chat_id, 'Could not create room') 352 | 353 | @logged_in 354 | @focused 355 | def forward_message_to_mc(self, msg, match): 356 | text = match.group('text') 357 | chat_id = msg['chat']['id'] 358 | from_user = msg['from'].get('username') 359 | 360 | if from_user and chat_id < 0: 361 | text = '{}: {}'.format(from_user, text) 362 | client = self._get_client(chat_id) 363 | 364 | client.send_message(text) 365 | 366 | @logged_in 367 | @focused 368 | def forward_photo_to_mc(self, msg): 369 | chat_id = msg['chat']['id'] 370 | client = self._get_client(chat_id) 371 | 372 | logger.debug(pprint_json(msg)) 373 | file_id = msg['photo'][-1]['file_id'] 374 | file_obj = self.getFile(file_id) 375 | file_path = file_obj['file_path'] 376 | file_name = os.path.split(file_path)[1] 377 | 378 | link = BOT_FILE_URL.format(token=self._token, file_path=file_path) 379 | download_file(link, os.path.join(self.config['media_dir'], file_name)) 380 | 381 | client.send_photo(os.path.join(self.config['media_dir'], file_name)) 382 | 383 | @logged_in 384 | @focused 385 | def forward_voice_to_mc(self, msg): 386 | chat_id = msg['chat']['id'] 387 | client = self._get_client(chat_id) 388 | 389 | file_id = msg['voice']['file_id'] 390 | file = self.getFile(file_id) 391 | file_path = file['file_path'] 392 | file_name = os.path.split(file_path)[1] 393 | 394 | link = BOT_FILE_URL.format(token=self._token, file_path=file_path) 395 | path = os.path.join(self.config['media_dir'], file_name) 396 | download_file(link, path) 397 | 398 | client.send_voice(path) 399 | 400 | @logged_in 401 | @focused 402 | def forward_video_to_mc(self, msg): 403 | chat_id = msg['chat']['id'] 404 | 405 | client = self._get_client(chat_id) 406 | 407 | file_id = msg['video']['file_id'] 408 | file = self.getFile(file_id) 409 | file_path = file['file_path'] 410 | file_name = os.path.split(file_path)[1] 411 | 412 | link = BOT_FILE_URL.format(token=self._token, file_path=file_path) 413 | path = os.path.join(self.config['media_dir'], file_name) 414 | download_file(link, path) 415 | 416 | client.send_video(path) 417 | 418 | # gifs are mp4 in telegram 419 | @logged_in 420 | @focused 421 | def forward_gif_to_mc(self, msg): 422 | chat_id = msg['chat']['id'] 423 | 424 | client = self._get_client(chat_id) 425 | 426 | file_id = msg['document']['file_id'] 427 | file = self.getFile(file_id) 428 | file_path = file['file_path'] 429 | file_name = os.path.split(file_path)[1] 430 | link = BOT_FILE_URL.format(token=self._token, file_path=file_path) 431 | path = os.path.join(self.config['media_dir'], file_name) 432 | download_file(link, path) 433 | 434 | client.send_video(path) 435 | 436 | def send_message(self, sender, msg, client): 437 | """Send message to telegram user. 438 | 439 | Args: 440 | sender (str): Name of the sender. 441 | msg (str): Text message. 442 | client (MatrigramClient): The client the message is originated in. 443 | 444 | Returns: 445 | 446 | """ 447 | chat_id = self._get_chat_id(client) 448 | if not chat_id: 449 | return 450 | 451 | self.sendChatAction(chat_id, 'typing') 452 | self.sendMessage(chat_id, "{}: {}".format(sender, msg)) 453 | 454 | def send_emote(self, sender, msg, client): 455 | chat_id = self._get_chat_id(client) 456 | if not chat_id: 457 | return 458 | 459 | self.sendChatAction(chat_id, 'typing') 460 | self.sendMessage(chat_id, '* {} {}'.format(sender, msg)) 461 | 462 | def send_topic(self, sender, topic, client): 463 | chat_id = self._get_chat_id(client) 464 | if not chat_id: 465 | return 466 | 467 | self.sendChatAction(chat_id, 'typing') 468 | self.sendMessage(chat_id, "{} changed topic to: \"{}\"".format(sender, topic)) 469 | 470 | def send_kick(self, room, client): 471 | logger.info('got kicked from %s', room) 472 | chat_id = self._get_chat_id(client) 473 | if not chat_id: 474 | return 475 | 476 | self.sendMessage(chat_id, 'You got kicked from {}'.format(room)) 477 | client.set_focus_room(None) 478 | 479 | @logged_in 480 | def set_name(self, msg, match): 481 | chat_id = msg['chat']['id'] 482 | client = self._get_client(chat_id) 483 | name = match.group('matrix_name') 484 | client.set_name(name) 485 | self.sendMessage(chat_id, 'Set matrix display name to: {}'.format(name)) 486 | 487 | @logged_in 488 | @focused 489 | def emote(self, msg, match): 490 | chat_id = msg['chat']['id'] 491 | client = self._get_client(chat_id) 492 | body = match.group('text') 493 | 494 | client.emote(body) 495 | 496 | def send_invite(self, client, room): 497 | logger.info('join room %s?', room) 498 | chat_id = self._get_chat_id(client) 499 | if not chat_id: 500 | return 501 | 502 | keyboard = { 503 | 'inline_keyboard': [ 504 | [ 505 | { 506 | 'text': 'Yes', 507 | 'callback_data': 'JOIN {}'.format(room), 508 | }, 509 | { 510 | 'text': 'No', 511 | 'callback_data': 'NOP', 512 | } 513 | ] 514 | ] 515 | } 516 | 517 | self.sendMessage(chat_id, 'You have been invited to room {}, accept?'.format(room), 518 | reply_markup=keyboard) 519 | 520 | # temporary fixes are permanent, lets do it the hard way 521 | def _workaround_sendPhoto(self, sender, path, chat_id): 522 | payload = { 523 | 'chat_id': chat_id, 524 | 'caption': sender, 525 | } 526 | 527 | files = { 528 | 'photo': open(path, 'rb') 529 | } 530 | 531 | base_url = BOT_BASE_URL.format(token=self._token, path='sendPhoto') 532 | requests.post(base_url, params=payload, files=files) 533 | 534 | def _workaround_sendAudio(self, sender, path, chat_id): 535 | payload = { 536 | 'chat_id': chat_id, 537 | 'caption': sender, 538 | } 539 | 540 | files = { 541 | 'audio': open(path, 'rb') 542 | } 543 | 544 | base_url = BOT_BASE_URL.format(token=self._token, path='sendAudio') 545 | requests.post(base_url, params=payload, files=files) 546 | 547 | def _workaround_sendVideo(self, sender, path, chat_id): 548 | payload = { 549 | 'chat_id': chat_id, 550 | 'caption': sender, 551 | } 552 | 553 | files = { 554 | 'video': open(path, 'rb') 555 | } 556 | 557 | base_url = BOT_BASE_URL.format(token=self._token, path='sendVideo') 558 | requests.post(base_url, params=payload, files=files) 559 | 560 | def send_photo(self, sender, path, client): 561 | logger.info('path = %s', path) 562 | chat_id = self._get_chat_id(client) 563 | if not chat_id: 564 | return 565 | 566 | self.sendChatAction(chat_id, 'upload_photo') 567 | self._workaround_sendPhoto(sender, path, chat_id) 568 | # self.sendPhoto(chat_id, open(path, 'rb')) 569 | 570 | def send_voice(self, sender, path, client): 571 | logger.info('path = %s', path) 572 | chat_id = self._get_chat_id(client) 573 | if not chat_id: 574 | return 575 | 576 | self.sendChatAction(chat_id, 'upload_audio') 577 | self._workaround_sendAudio(sender, path, chat_id) 578 | 579 | def send_video(self, sender, path, client): 580 | logger.info('path = %s', path) 581 | chat_id = self._get_chat_id(client) 582 | if not chat_id: 583 | return 584 | 585 | self.sendChatAction(chat_id, 'upload_video') 586 | self._workaround_sendVideo(sender, path, chat_id) 587 | 588 | def relay_typing(self, chat_id): 589 | while True: 590 | with self.users_lock: 591 | if not self.users[chat_id]['should_type']: 592 | return 593 | self.sendChatAction(chat_id, 'typing') 594 | time.sleep(2) 595 | 596 | def start_typing_thread(self, client): 597 | chat_id = self._get_chat_id(client) 598 | 599 | with self.users_lock: 600 | if self.users[chat_id]['typing_thread']: 601 | return 602 | 603 | typing_thread = Thread(target=self.relay_typing, args=(chat_id,)) 604 | self.users[chat_id]['should_type'] = True 605 | typing_thread.start() 606 | self.users[chat_id]['typing_thread'] = typing_thread 607 | 608 | def stop_typing_thread(self, client): 609 | chat_id = self._get_chat_id(client) 610 | 611 | with self.users_lock: 612 | if not self.users[chat_id]['typing_thread']: 613 | return 614 | 615 | typing_thread = self.users[chat_id]['typing_thread'] 616 | self.users[chat_id]['should_type'] = False 617 | typing_thread.join() 618 | 619 | with self.users_lock: 620 | self.users[chat_id]['typing_thread'] = None 621 | 622 | def _get_client(self, chat_id): 623 | """Get matrigram client. 624 | 625 | Args: 626 | chat_id: Telegram user id. 627 | 628 | Returns: 629 | MatrigramClient: The client associated to the telegram user with `chat_id`. 630 | """ 631 | try: 632 | return self.users[chat_id]['client'] 633 | except KeyError: 634 | logger.error('chat_id doesnt exist?') 635 | return None 636 | 637 | def _get_chat_id(self, client): 638 | """Get telegram id associated with client. 639 | 640 | Args: 641 | client (MatrigramClient): The client to be queried. 642 | 643 | Returns: 644 | str: The `chat_id` associated to the client. 645 | """ 646 | for chat_id, user in self.users.items(): 647 | if user['client'] == client: 648 | return chat_id 649 | 650 | logger.error('client without user?') 651 | return None 652 | --------------------------------------------------------------------------------