├── .gitignore
├── .readthedocs.yaml
├── CHANGELOG.md
├── LICENSE
├── MANIFEST.in
├── README.md
├── docs
├── conf.py
├── configuration.rst
├── developer_guide.rst
├── index.rst
├── installation.rst
└── user_guide.rst
├── pyproject.toml
├── src
└── err-backend-mattermost
│ ├── __init__.py
│ ├── err-backend-mattermost.plug
│ ├── err-backend-mattermost.py
│ └── mattermostlib
│ ├── mattermostPerson.py
│ ├── mattermostRoom.py
│ └── mattermostRoomOccupant.py
└── tests
├── config.py
├── docker-compose.yml
├── init_mattermost.sh
├── plugins
├── test.plug
└── test.py
└── requirements.txt
/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by .ignore support plugin (hsz.mobi)
2 | ### JetBrains template
3 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
4 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
5 |
6 | # User-specific stuff:
7 | .idea/workspace.xml
8 | .idea/tasks.xml
9 |
10 | # Sensitive or high-churn files:
11 | .idea/dataSources/
12 | .idea/dataSources.ids
13 | .idea/dataSources.xml
14 | .idea/dataSources.local.xml
15 | .idea/sqlDataSources.xml
16 | .idea/dynamic.xml
17 | .idea/uiDesigner.xml
18 |
19 | # Gradle:
20 | .idea/gradle.xml
21 | .idea/libraries
22 |
23 | # Mongo Explorer plugin:
24 | .idea/mongoSettings.xml
25 |
26 | ## File-based project format:
27 | *.iws
28 |
29 | ## Plugin-specific files:
30 |
31 | # IntelliJ
32 | /out/
33 |
34 | # mpeltonen/sbt-idea plugin
35 | .idea_modules/
36 |
37 | # JIRA plugin
38 | atlassian-ide-plugin.xml
39 |
40 | # Crashlytics plugin (for Android Studio and IntelliJ)
41 | com_crashlytics_export_strings.xml
42 | crashlytics.properties
43 | crashlytics-build.properties
44 | fabric.properties
45 | ### VirtualEnv template
46 | # Virtualenv
47 | # http://iamzed.com/2009/05/07/a-primer-on-virtualenv/
48 | .Python
49 | [Bb]in
50 | [Ii]nclude
51 | [Ll]ib
52 | [Ll]ib64
53 | [Ll]ocal
54 | [Ss]cripts
55 | pyvenv.cfg
56 | .venv
57 | pip-selfcheck.json
58 | ### Python template
59 | # Byte-compiled / optimized / DLL files
60 | __pycache__/
61 | *.py[cod]
62 | *$py.class
63 |
64 | # C extensions
65 | *.so
66 |
67 | # Distribution / packaging
68 | env/
69 | build/
70 | develop-eggs/
71 | dist/
72 | downloads/
73 | eggs/
74 | .eggs/
75 | lib/
76 | lib64/
77 | parts/
78 | sdist/
79 | var/
80 | *.egg-info/
81 | .installed.cfg
82 | *.egg
83 |
84 | # PyInstaller
85 | # Usually these files are written by a python script from a template
86 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
87 | *.manifest
88 | *.spec
89 |
90 | # Installer logs
91 | pip-log.txt
92 | pip-delete-this-directory.txt
93 |
94 | # Unit test / coverage reports
95 | htmlcov/
96 | .tox/
97 | .coverage
98 | .coverage.*
99 | .cache
100 | nosetests.xml
101 | coverage.xml
102 | *,cover
103 | .hypothesis/
104 |
105 | # Translations
106 | *.mo
107 | *.pot
108 |
109 | # Django stuff:
110 | *.log
111 | local_settings.py
112 |
113 | # Flask stuff:
114 | instance/
115 | .webassets-cache
116 |
117 | # Scrapy stuff:
118 | .scrapy
119 |
120 | # Sphinx documentation
121 | docs/_build/
122 |
123 | # PyBuilder
124 | target/
125 |
126 | # Jupyter Notebook
127 | .ipynb_checkpoints
128 |
129 | # pyenv
130 | .python-version
131 |
132 | # celery beat schedule file
133 | celerybeat-schedule
134 |
135 | # dotenv
136 | .env
137 |
138 | # virtualenv
139 | .venv/
140 | venv/
141 | ENV/
142 |
143 | # Spyder project settings
144 | .spyderproject
145 |
146 | # Rope project settings
147 | .ropeproject
148 | /errbot-root/
149 |
--------------------------------------------------------------------------------
/.readthedocs.yaml:
--------------------------------------------------------------------------------
1 | # .readthedocs.yaml
2 | # Read the Docs configuration file
3 | # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
4 |
5 | # Required
6 | version: 2
7 |
8 | # Set the version of Python and other tools you might need
9 | build:
10 | os: ubuntu-22.04
11 | tools:
12 | python: "3.11"
13 |
14 | # Build documentation in the docs/ directory with Sphinx
15 | sphinx:
16 | configuration: docs/conf.py
17 |
18 | # We recommend specifying your dependencies to enable reproducible builds:
19 | # https://docs.readthedocs.io/en/stable/guides/reproducible-builds.html
20 | # python:
21 | # install:
22 | # - requirements: docs/requirements.txt
23 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 | All notable changes to this project will be documented in this file.
3 |
4 | The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
5 | and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
6 |
7 | ## [3.0.0] 2021-10-20
8 |
9 | ### Added
10 | - restructured code to use source layout for pypi packaging.
11 | - documentation added for readthedocs.
12 |
13 | ### Changed
14 |
15 | ### Removed
16 |
17 |
18 | ## [2.1.0] 2021-11-27
19 |
20 | ### Added
21 | - create or use thread when sending message with `in_reply_to`.
22 | - support of `DIVERT_TO_THREAD` option.
23 | - ability to define custom event handlers.
24 | - email field to Person object.
25 | - cache attributes in order to prevent excessive http requests for Person object.
26 |
27 | ### Changed
28 | - room occupant no longer processed as list type.
29 | - code formatted with black.
30 | - message size limt to 16377 characters.
31 | - return any combination of first name/surname for Person.fullname without trailing or leading space.
32 | - moved project to official errbotio organisation https://github.com/errbotio/errbot-mattermost-backend.git
33 |
34 | ### Removed
35 |
36 |
37 | ## [2.0.2] 2017-11-27
38 |
39 | ### Added
40 |
41 | ### Changed
42 | - channelid to be optional to join a room.
43 |
44 | ### Removed
45 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | err-backend-mattermost Copyright (C) 2022 Errbot backend contributors
656 | err-backend-mattermost Copyright (C) 2017-2021 Christian Plümer and contributors
657 |
658 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
659 | This is free software, and you are welcome to redistribute it
660 | under certain conditions; type `show c' for details.
661 |
662 | The hypothetical commands `show w' and `show c' should show the appropriate
663 | parts of the General Public License. Of course, your program's commands
664 | might be different; for a GUI interface, you would use an "about box".
665 |
666 | You should also get your employer (if you work as a programmer) or school,
667 | if any, to sign a "copyright disclaimer" for the program, if necessary.
668 | For more information on this, and how to apply and follow the GNU GPL, see
669 | .
670 |
671 | The GNU General Public License does not permit incorporating your program
672 | into proprietary programs. If your program is a subroutine library, you
673 | may consider it more useful to permit linking proprietary applications with
674 | the library. If this is what you want to do, use the GNU Lesser General
675 | Public License instead of this License. But first, please read
676 | .
677 |
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include src/err-backend-mattermost/*.plug
2 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Mattermost backend for Errbot
2 |
3 | This is the Mattermost backend for errbot.
4 |
5 | # Documentation
6 |
7 | Visit the [official documentation](https://err-backend-mattermost.readthedocs.io/) where you'll find information on the following topics:
8 | - Installation
9 | - Configuration
10 | - User Guide
11 | - Developer Guide
12 |
13 |
--------------------------------------------------------------------------------
/docs/conf.py:
--------------------------------------------------------------------------------
1 | # Configuration file for the Sphinx documentation builder.
2 | #
3 | # This file only contains a selection of the most common options. For a full
4 | # list see the documentation:
5 | # http://www.sphinx-doc.org/en/master/config
6 |
7 | # -- Path setup --------------------------------------------------------------
8 |
9 | # If extensions (or modules to document with autodoc) are in another directory,
10 | # add these directories to sys.path here. If the directory is relative to the
11 | # documentation root, use os.path.abspath to make it absolute, like shown here.
12 | #
13 | # import os
14 | # import sys
15 | # sys.path.insert(0, os.path.abspath('.'))
16 |
17 |
18 | # -- Project information -----------------------------------------------------
19 |
20 | project = "errbot-backend-mattermost"
21 | copyright = "2019-2023, errbot-backend-mattermost contributors"
22 | author = "errbot-backend-mattermost contributors"
23 |
24 | # The full version, including alpha/beta/rc tags
25 | release = "3.0.0"
26 |
27 |
28 | # -- General configuration ---------------------------------------------------
29 |
30 | master_doc = "index"
31 | # Add any Sphinx extension module names here, as strings. They can be
32 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
33 | # ones.
34 | extensions = []
35 |
36 | # Add any paths that contain templates here, relative to this directory.
37 | templates_path = ["_templates"]
38 |
39 | # List of patterns, relative to source directory, that match files and
40 | # directories to ignore when looking for source files.
41 | # This pattern also affects html_static_path and html_extra_path.
42 | exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
43 |
44 |
45 | # -- Options for HTML output -------------------------------------------------
46 |
47 | # The theme to use for HTML and HTML Help pages. See the documentation for
48 | # a list of builtin themes.
49 | #
50 | # html_theme = 'alabaster'
51 | html_theme = "sphinx_rtd_theme"
52 |
53 | # Add any paths that contain custom static files (such as style sheets) here,
54 | # relative to this directory. They are copied after the builtin static files,
55 | # so a file named "default.css" will overwrite the builtin "default.css".
56 | html_static_path = ["_static"]
57 |
--------------------------------------------------------------------------------
/docs/configuration.rst:
--------------------------------------------------------------------------------
1 | .. _configuration:
2 |
3 | Configuration
4 | ========================================================================
5 |
6 | To configure mattermost as errbot's backend, you must edit `config.py`, which is created as part of the errbot initialisation process or downloaded from the official errbot documentation.
7 |
8 |
9 | .. code-block:: python
10 |
11 | BACKEND = 'Mattermost'
12 | BOT_EXTRA_BACKEND_DIR = '/path/to/backends'
13 |
14 | BOT_ADMINS = ('@yourname') # Names need the @ in front!
15 |
16 | BOT_IDENTITY = {
17 | # Required
18 | "team": "nameoftheteam",
19 | "server": "mattermost.server.com",
20 | # For the login, either
21 | "login": "bot@email.de",
22 | "password": "botpassword",
23 | # Or, if you have a personal access token
24 | "token": "YourPersonalAccessToken",
25 | # Optional
26 | "insecure": False, # Default = False. Set to true for self signed certificates
27 | "scheme": "https", # Default = https
28 | "port": 8065, # Default = 8065
29 | "timeout": 30, # Default = 30. If the web server disconnects idle connections later/earlier change this value
30 | "cards_hook": "incomingWebhookId" # Needed for cards/attachments
31 | }
32 |
33 |
34 | .. note:: The above configuration example only shows mattermost settings, but all errbot configuration settings. Use the official errbot documentation to complete the above example.
35 |
36 | .. important:: Some Mattermost actions can only be performed with administrator rights. If the bot has problems performing an action, check the bot account permissions and grant the appropriate rights.
37 |
--------------------------------------------------------------------------------
/docs/developer_guide.rst:
--------------------------------------------------------------------------------
1 | .. _developer_guide:
2 |
3 | Developer Guide
4 | ========================================================================
5 |
6 | The process for contributing to the mattermost backend follows the traditional github methodology.
7 |
8 | 1. Fork the github project to your github account.
9 | 2. Clone the forked repository to your development machine.
10 | 3. Create a branch for changes in your locally cloned repository.
11 | 4. Develop feature/fix/change in your branch.
12 | 5. Push work from your branch to your forked repository
13 | 6. Open pull request from your forked repository to the official err-backend-mattermost repository.
14 |
--------------------------------------------------------------------------------
/docs/index.rst:
--------------------------------------------------------------------------------
1 |
2 | .. title:: err-backend-mattermost documentation
3 |
4 | Errbot Mattermost Backend Documentation
5 | ========================================================================
6 |
7 | Welcome to the ``err-backend-mattermost`` documentation page. You'll be able to find
8 | installation instructions, configuration information and examples of using some of the backend's features.
9 |
10 | The ``err-backend-mattermost`` backend lets you connect errbot to the `Mattermost `_ open source collaboration platform.
11 |
12 | .. toctree::
13 | :maxdepth: 2
14 | :caption: Contents:
15 |
16 | installation.rst
17 | configuration.rst
18 | user_guide.rst
19 | developer_guide.rst
20 |
21 |
22 | Indices and tables
23 | ==================
24 |
25 | * :ref:`genindex`
26 | * :ref:`modindex`
27 | * :ref:`search`
28 |
--------------------------------------------------------------------------------
/docs/installation.rst:
--------------------------------------------------------------------------------
1 | .. _installation:
2 |
3 | Installation
4 | ========================================================================
5 |
6 | .. contents:: :local:
7 |
8 | Requirements
9 | ------------------------------------------------------------------------
10 |
11 | - Mattermost with APIv4
12 | - Python >= 3.7
13 | - websockets 3.2
14 | - `mattermostdriver `_ > 4.0
15 |
16 |
17 | Python Virtual Environment
18 | ------------------------------------------------------------------------
19 |
20 | These instructions assume you have a mattermost instance up and running with a bot account configured. For information on how to setup the bot account see https://developers.mattermost.com/integrate/reference/bot-accounts/
21 |
22 | 1. Create a virtual environment for errbot.
23 | ::
24 |
25 | python3 -m venv
26 | source /bin/activate
27 |
28 | 2. Install errbot and mattermost backend.
29 | ::
30 |
31 | pip install errbot mattermost
32 |
33 | 3. Initialise errbot and configure mattermost.
34 | ::
35 |
36 | errbot --init
37 |
38 | 4. See the :ref:`configuration` section for configuration details.
39 |
--------------------------------------------------------------------------------
/docs/user_guide.rst:
--------------------------------------------------------------------------------
1 | .. _user_guide:
2 |
3 | User Guide
4 | ========================================================================
5 |
6 | .. contents:: :local:
7 |
8 | Cards/Attachments
9 | ------------------------------------------------------------------------
10 |
11 | Cards are called _attachments_ in Mattermost.
12 |
13 | If you want to send attachments, you need to create an incoming Webhook in Mattermost
14 | and add the webhook id to your errbot `config.py` in `BOT_IDENTITY`.
15 |
16 | This is not an ideal solution, but AFAIK Mattermost does not support sending attachments
17 | over the api like slack does.
18 |
19 |
20 | APIv3
21 | ------------------------------------------------------------------------
22 | Mattermost has deprecated the v3 API. If you are still running APIv3, you're strongly encourage to upgrade.
23 | Despite this, there is an APIv3 branch in the github repository that you can try but keep in mind that it is no longer supported and not guaranteed to work!
24 |
25 | .. important:: The `BOT_IDENTITY` config options are different for APIv3 and APIv4!
26 |
27 |
28 | Known (possible) Issues
29 | ------------------------------------------------------------------------
30 |
31 | - Channel mentions in messages aren't accounted for and it is unclear if they need to be. If you think they should be or you've encountered an error, please open an issue against the err-backend-mattermost github repository.
32 |
33 |
34 | F.A.Q.
35 | ------------------------------------------------------------------------
36 |
37 | The Bot does not answer my direct messages
38 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
39 | If you have multiple teams, check that you are both members of the same team!
40 |
41 |
42 | Special thanks
43 | ------------------------------------------------------------------------
44 |
45 | **Thanks** to http://errbot.io/ the contributors. The mattermost backend has been derived from the backends from there.
46 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [build-system]
2 | requires = [
3 | "setuptools>=61.0"
4 | ]
5 | build-backend = "setuptools.build_meta"
6 |
7 | [project]
8 | name = "err-backend-mattermost"
9 | version = "3.0.0"
10 | authors = [{ name="Errbot maintainers", email="noreply@errbot.io" }]
11 | keywords = [
12 | "errbot",
13 | "mattermost",
14 | ]
15 | description = "Mattermost backend for Errbot"
16 | readme = "README.md"
17 | requires-python = ">=3.7"
18 |
19 | license = {text = "GPL-3.0"}
20 |
21 | classifiers = [
22 | "Programming Language :: Python :: 3",
23 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
24 | "Operating System :: OS Independent",
25 | ]
26 |
27 | dependencies = [
28 | "mattermostdriver>=4.0",
29 | ]
30 |
31 | [project.urls]
32 | "Documentaion" = "https://err-backend-mattermost.readthedocs.io/"
33 | "Bug Tracker" = "https://github.com/errbotio/err-backend-mattermost/issues"
34 |
35 | [tool.setuptools]
36 | # available as beta since setuptools version 61.0.0
37 | include-package-data = true
38 |
--------------------------------------------------------------------------------
/src/err-backend-mattermost/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/errbotio/err-backend-mattermost/7f1cbd2240c973f424cde7e326eaed4f09a995a6/src/err-backend-mattermost/__init__.py
--------------------------------------------------------------------------------
/src/err-backend-mattermost/err-backend-mattermost.plug:
--------------------------------------------------------------------------------
1 | [Core]
2 | Name = Mattermost
3 | Module = err-backend-mattermost
4 |
5 | [Documentation]
6 | Description = Mattermost backend for Errbot.
7 | Author = Christian Plümer and Errbot backend contributors
8 | Version = 3.0.0
9 | Website = https://github.com/errbotio/errbot-mattermost-backend
10 |
--------------------------------------------------------------------------------
/src/err-backend-mattermost/err-backend-mattermost.py:
--------------------------------------------------------------------------------
1 | import json
2 | import logging
3 | from functools import lru_cache
4 |
5 | from errbot.backends.base import (
6 | Message,
7 | Presence,
8 | ONLINE,
9 | AWAY,
10 | UserDoesNotExistError,
11 | RoomDoesNotExistError,
12 | RoomOccupant,
13 | Card,
14 | )
15 | from errbot.core import ErrBot
16 | from errbot.rendering import md
17 | from errbot.utils import split_string_after
18 | from mattermostdriver import Driver
19 | from mattermostdriver.exceptions import (
20 | InvalidOrMissingParameters,
21 | NotEnoughPermissions,
22 | ContentTooLarge,
23 | FeatureDisabled,
24 | NoAccessTokenProvided,
25 | )
26 |
27 | from mattermostlib.mattermostPerson import MattermostPerson
28 | from mattermostlib.mattermostRoom import MattermostRoom
29 | from mattermostlib.mattermostRoomOccupant import MattermostRoomOccupant
30 |
31 | log = logging.getLogger("errbot.backends.mattermost")
32 |
33 | # Default websocket timeout - this is needed to send a heartbeat
34 | # to keep the connection alive
35 | DEFAULT_TIMEOUT = 30
36 |
37 | COLORS = {
38 | "white": "#FFFFFF",
39 | "cyan": "#00FFFF",
40 | "blue": "#0000FF",
41 | "red": "#FF0000",
42 | "green": "#008000",
43 | "yellow": "#FFA500",
44 | }
45 |
46 |
47 | class MattermostBackend(ErrBot):
48 | def __init__(self, config):
49 | super().__init__(config)
50 | identity = config.BOT_IDENTITY
51 | self._login = identity.get("login", None)
52 | self._password = identity.get("password", None)
53 | self._personal_access_token = identity.get("token", None)
54 | self._mfa_token = identity.get("mfa_token", None)
55 | self.team = identity.get("team")
56 | self._scheme = identity.get("scheme", "https")
57 | self._port = identity.get("port", 8065)
58 | self.cards_hook = identity.get("cards_hook", None)
59 | self.url = identity.get("server").rstrip("/")
60 | self.insecure = identity.get("insecure", False)
61 | self.timeout = identity.get("timeout", DEFAULT_TIMEOUT)
62 | self.teamid = ""
63 | self.token = ""
64 | self.bot_identifier = None
65 | self.driver = None
66 | self.md = md()
67 | self.event_handlers = {
68 | "posted": [self._message_event_handler],
69 | "status_change": [self._status_change_event_handler],
70 | "hello": [self._hello_event_handler],
71 | "user_added": [self._room_joined_event_handler],
72 | "user_removed": [self._room_left_event_handler],
73 | }
74 |
75 | def set_message_size_limit(self, limit=16377, hard_limit=16383):
76 | """
77 | Mattermost message limit is 16383 chars, need to leave some space for
78 | backticks when messages are split
79 | """
80 | super().set_message_size_limit(limit, hard_limit)
81 |
82 | @property
83 | def userid(self):
84 | return "{}".format(self.bot_identifier.userid)
85 |
86 | @property
87 | def mode(self):
88 | return "mattermost"
89 |
90 | def username_to_userid(self, name):
91 | """Converts a name prefixed with @ to the userid"""
92 | name = name.lstrip("@")
93 | user = self.driver.users.get_user_by_username(username=name)
94 | if user is None:
95 | raise UserDoesNotExistError("Cannot find user {}".format(name))
96 | return user["id"]
97 |
98 | def register_handler(self, event, handler):
99 | if event not in self.event_handlers:
100 | self.event_handlers[event] = []
101 | self.event_handlers[event].append(handler)
102 |
103 | async def mattermost_event_handler(self, payload):
104 | if not payload:
105 | return
106 |
107 | payload = json.loads(payload)
108 | if "event" not in payload:
109 | log.debug("Message contains no event: {}".format(payload))
110 | return
111 |
112 | event = payload["event"]
113 | event_handlers = self.event_handlers.get(event)
114 |
115 | if event_handlers is None:
116 | log.debug("No event handlers available for {}, ignoring.".format(event))
117 | return
118 | # noinspection PyBroadException
119 | for event_handler in event_handlers:
120 | try:
121 | event_handler(payload)
122 | except Exception:
123 | log.exception("{} event handler raised an exception".format(event))
124 |
125 | def _room_joined_event_handler(self, message):
126 | log.debug("User added to channel")
127 | if message["data"]["user_id"] == self.userid:
128 | self.callback_room_joined(self)
129 |
130 | def _room_left_event_handler(self, message):
131 | log.debug("User removed from channel")
132 | if message["broadcast"]["user_id"] == self.userid:
133 | self.callback_room_left(self)
134 |
135 | def _message_event_handler(self, message):
136 | log.debug(message)
137 | data = message["data"]
138 |
139 | # In some cases (direct messages) team_id is an empty string
140 | if data["team_id"] != "" and self.teamid != data["team_id"]:
141 | log.info(
142 | "Message came from another team ({}), ignoring...".format(
143 | data["team_id"]
144 | )
145 | )
146 | return
147 |
148 | broadcast = message["broadcast"]
149 |
150 | if "channel_id" in data:
151 | channelid = data["channel_id"]
152 | elif "channel_id" in broadcast:
153 | channelid = broadcast["channel_id"]
154 | else:
155 | log.error("Couldn't find a channelid for event {}".format(message))
156 | return
157 |
158 | channel_type = data["channel_type"]
159 |
160 | if channel_type != "D":
161 | channel = data["channel_name"]
162 | else:
163 | channel = channelid
164 |
165 | text = ""
166 | post_id = ""
167 | file_ids = None
168 | userid = None
169 |
170 | if "post" in data:
171 | post = json.loads(data["post"])
172 | text = post["message"]
173 | userid = post["user_id"]
174 | if "file_ids" in post:
175 | file_ids = post["file_ids"]
176 | post_id = post["id"]
177 | if "type" in post and post["type"] == "system_add_remove":
178 | log.info("Ignoring message from System")
179 | return
180 |
181 | if "user_id" in data:
182 | userid = data["user_id"]
183 |
184 | if not userid:
185 | log.error("No userid in event {}".format(message))
186 | return
187 |
188 | mentions = []
189 | if "mentions" in data:
190 | # TODO: Only user, not channel mentions are in here at the moment
191 | mentions = self.mentions_build_identifier(json.loads(data["mentions"]))
192 |
193 | # Thread root post id
194 | root_id = post.get("root_id", "")
195 | if root_id == "":
196 | root_id = post_id
197 |
198 | msg = Message(
199 | text,
200 | extras={
201 | "id": post_id,
202 | "root_id": root_id,
203 | "mattermost_event": message,
204 | "url": "{scheme:s}://{domain:s}:{port:s}/{teamname:s}/pl/{postid:s}".format(
205 | scheme=self.driver.options["scheme"],
206 | domain=self.driver.options["url"],
207 | port=str(self.driver.options["port"]),
208 | teamname=self.team,
209 | postid=post_id,
210 | ),
211 | },
212 | )
213 | if file_ids:
214 | msg.extras["attachments"] = file_ids
215 |
216 | # TODO: Slack handles bots here, but I am not sure if bot users is a concept in mattermost
217 | if channel_type == "D":
218 | msg.frm = MattermostPerson(
219 | self.driver, userid=userid, channelid=channelid, teamid=self.teamid
220 | )
221 | msg.to = MattermostPerson(
222 | self.driver,
223 | userid=self.bot_identifier.userid,
224 | channelid=channelid,
225 | teamid=self.teamid,
226 | )
227 | elif channel_type == "O" or channel_type == "P":
228 | msg.frm = MattermostRoomOccupant(
229 | self.driver,
230 | userid=userid,
231 | channelid=channelid,
232 | teamid=self.teamid,
233 | bot=self,
234 | )
235 | msg.to = MattermostRoom(channel, teamid=self.teamid, bot=self)
236 | else:
237 | log.warning(
238 | "Unknown channel type '{}'! Unable to handle {}.".format(
239 | channel_type, channel
240 | )
241 | )
242 | return
243 |
244 | self.callback_message(msg)
245 |
246 | if mentions:
247 | self.callback_mention(msg, mentions)
248 |
249 | def _status_change_event_handler(self, message):
250 | """Event handler for the 'presence_change' event"""
251 | idd = MattermostPerson(self.driver, message["data"]["user_id"])
252 | status = message["data"]["status"]
253 | if status == "online":
254 | status = ONLINE
255 | elif status == "away":
256 | status = AWAY
257 | else:
258 | log.error(
259 | "It appears the Mattermost API changed, I received an unknown status type %s"
260 | % status
261 | )
262 | status = ONLINE
263 | self.callback_presence(Presence(identifier=idd, status=status))
264 |
265 | def _hello_event_handler(self, message):
266 | """Event handler for the 'hello' event"""
267 | self.connect_callback()
268 | self.callback_presence(Presence(identifier=self.bot_identifier, status=ONLINE))
269 |
270 | @lru_cache(1024)
271 | def get_direct_channel(self, userid, other_user_id):
272 | """
273 | Get the direct channel to another user.
274 | If it does not exist, it will be created.
275 | """
276 | try:
277 | return self.driver.channels.create_direct_message_channel(
278 | options=[userid, other_user_id]
279 | )
280 | except (InvalidOrMissingParameters, NotEnoughPermissions):
281 | raise RoomDoesNotExistError(
282 | "Could not find Direct Channel for users with ID {} and {}".format(
283 | userid, other_user_id
284 | )
285 | )
286 |
287 | def build_identifier(self, txtrep):
288 | """
289 | Convert a textual representation into a
290 | :class:`~MattermostPerson` or :class:`~MattermostRoom`
291 |
292 | Supports strings with the following formats::
293 |
294 | @username
295 | ~channelname
296 | channelid
297 | """
298 | txtrep = txtrep.strip()
299 | if txtrep.startswith("~"):
300 | # Channel
301 | channelid = self.channelname_to_channelid(txtrep[1:])
302 | if channelid is not None:
303 | return MattermostRoom(channelid=channelid, teamid=self.teamid, bot=self)
304 | else:
305 | # Assuming either a channelid or a username
306 | if txtrep.startswith("@"):
307 | # Username
308 | userid = self.username_to_userid(txtrep[1:])
309 | else:
310 | # Channelid
311 | userid = txtrep
312 |
313 | if userid is not None:
314 | return MattermostPerson(
315 | self.driver,
316 | userid=userid,
317 | channelid=self.get_direct_channel(self.userid, userid)["id"],
318 | teamid=self.teamid,
319 | )
320 | raise Exception("Invalid or unsupported Mattermost identifier: %s" % txtrep)
321 |
322 | def mentions_build_identifier(self, mentions):
323 | identifier = []
324 | for mention in mentions:
325 | if mention != self.bot_identifier.userid:
326 | identifier.append(self.build_identifier(mention))
327 | return identifier
328 |
329 | def serve_once(self):
330 | self.driver = Driver(
331 | {
332 | "scheme": self._scheme,
333 | "url": self.url,
334 | "port": self._port,
335 | "verify": not self.insecure,
336 | "timeout": self.timeout,
337 | "login_id": self._login,
338 | "password": self._password,
339 | "token": self._personal_access_token,
340 | "mfa_token": self._mfa_token,
341 | }
342 | )
343 | self.driver.login()
344 |
345 | self.teamid = self.driver.teams.get_team_by_name(name=self.team)["id"]
346 | userid = self.driver.users.get_user(user_id="me")["id"]
347 |
348 | self.token = self.driver.client.token
349 |
350 | self.bot_identifier = MattermostPerson(
351 | self.driver, userid=userid, teamid=self.teamid
352 | )
353 |
354 | # noinspection PyBroadException
355 | try:
356 | loop = self.driver.init_websocket(
357 | event_handler=self.mattermost_event_handler
358 | )
359 | self.reset_reconnection_count()
360 | loop.run_forever()
361 | except KeyboardInterrupt:
362 | log.info("Interrupt received, shutting down..")
363 | return True
364 | except Exception:
365 | log.exception("Error reading from RTM stream:")
366 | finally:
367 | log.debug("Triggering disconnect callback")
368 | self.disconnect_callback()
369 |
370 | def _prepare_message(self, message):
371 | to_name = ""
372 | if message.is_group:
373 | to_channel_id = message.to.id
374 | if message.to.name:
375 | to_name = message.to.name
376 | else:
377 | self.channelid_to_channelname(channelid=to_channel_id)
378 | else:
379 | to_name = message.to.username
380 |
381 | if isinstance(
382 | message.to, RoomOccupant
383 | ): # private to a room occupant -> this is a divert to private !
384 | log.debug(
385 | "This is a divert to private message, sending it directly to the user."
386 | )
387 | channel = self.get_direct_channel(
388 | self.userid, self.username_to_userid(to_name)
389 | )
390 | to_channel_id = channel["id"]
391 | else:
392 | to_channel_id = message.to.channelid
393 | return to_name, to_channel_id
394 |
395 | def send_message(self, message):
396 | super().send_message(message)
397 | try:
398 | to_name, to_channel_id = self._prepare_message(message)
399 |
400 | message_type = "direct" if message.is_direct else "channel"
401 | log.debug(
402 | "Sending %s message to %s (%s)" % (message_type, to_name, to_channel_id)
403 | )
404 |
405 | body = self.md.convert(message.body)
406 | log.debug("Message size: %d" % len(body))
407 |
408 | parts = self.prepare_message_body(body, self.message_size_limit)
409 |
410 | root_id = None
411 | if message.parent is not None:
412 | root_id = message.parent.extras.get("root_id")
413 |
414 | for part in parts:
415 | self.driver.posts.create_post(
416 | options={
417 | "channel_id": to_channel_id,
418 | "message": part,
419 | "root_id": root_id,
420 | }
421 | )
422 | except (InvalidOrMissingParameters, NotEnoughPermissions):
423 | log.exception(
424 | "An exception occurred while trying to send the following message "
425 | "to %s: %s" % (to_name, message.body)
426 | )
427 |
428 | def send_card(self, card: Card):
429 | if isinstance(card.to, RoomOccupant):
430 | card.to = card.to.room
431 |
432 | to_humanreadable, to_channel_id = self._prepare_message(card)
433 |
434 | attachment = {}
435 | if card.summary:
436 | attachment["pretext"] = card.summary
437 | if card.title:
438 | attachment["title"] = card.title
439 | if card.link:
440 | attachment["title_link"] = card.link
441 | if card.image:
442 | attachment["image_url"] = card.image
443 | if card.thumbnail:
444 | attachment["thumb_url"] = card.thumbnail
445 | attachment["text"] = card.body
446 |
447 | if card.color:
448 | attachment["color"] = (
449 | COLORS[card.color] if card.color in COLORS else card.color
450 | )
451 |
452 | if card.fields:
453 | attachment["fields"] = [
454 | {"title": key, "value": value, "short": True}
455 | for key, value in card.fields
456 | ]
457 |
458 | data = {"attachments": [attachment]}
459 |
460 | if card.to:
461 | if isinstance(card.to, MattermostRoom):
462 | data["channel"] = card.to.name
463 |
464 | try:
465 | log.debug("Sending data:\n%s", data)
466 | # We need to send a webhook - mattermost has no api endpoint for attachments/cards
467 | # For this reason, we need to build our own url, since we need /hooks and not /api/v4
468 | # Todo: Reminder to check if this is still the case
469 | self.driver.webhooks.call_webhook(self.cards_hook, options=data)
470 | except (
471 | InvalidOrMissingParameters,
472 | NotEnoughPermissions,
473 | ContentTooLarge,
474 | FeatureDisabled,
475 | NoAccessTokenProvided,
476 | ):
477 | log.exception(
478 | "An exception occurred while trying to send a card to %s.[%s]"
479 | % (to_humanreadable, card)
480 | )
481 |
482 | def prepare_message_body(self, body, size_limit):
483 | """
484 | Returns the parts of a message chunked and ready for sending.
485 | This is a staticmethod for easier testing.
486 | Args:
487 | body (str)
488 | size_limit (int): chunk the body into sizes capped at this maximum
489 | Returns:
490 | [str]
491 | """
492 | fixed_format = body.startswith("```") # hack to fix the formatting
493 | parts = list(split_string_after(body, size_limit))
494 |
495 | if len(parts) == 1:
496 | # If we've got an open fixed block, close it out
497 | if parts[0].count("```") % 2 != 0:
498 | parts[0] += "\n```\n"
499 | else:
500 | for i, part in enumerate(parts):
501 | starts_with_code = part.startswith("```")
502 |
503 | # If we're continuing a fixed block from the last part
504 | if fixed_format and not starts_with_code:
505 | parts[i] = "```\n" + part
506 |
507 | # If we've got an open fixed block, close it out
508 | if parts[i].count("```") % 2 != 0:
509 | parts[i] += "\n```\n"
510 |
511 | return parts
512 |
513 | def change_presence(self, status: str = ONLINE, message: str = ""):
514 | pass # Mattermost does not have a request/websocket event to change the presence
515 |
516 | def is_from_self(self, message: Message):
517 | return self.bot_identifier.userid == message.frm.userid
518 |
519 | def shutdown(self):
520 | self.driver.logout()
521 | super().shutdown()
522 |
523 | def query_room(self, room):
524 | """Room can either be a name or a channelid"""
525 | return MattermostRoom(room, teamid=self.teamid, bot=self)
526 |
527 | def prefix_groupchat_reply(self, message: Message, identifier):
528 | super().prefix_groupchat_reply(message, identifier)
529 | message.body = "@{0}: {1}".format(identifier.nick, message.body)
530 |
531 | def build_reply(self, message, text=None, private=False, threaded=False):
532 | response = self.build_message(text)
533 | response.frm = self.bot_identifier
534 | if private:
535 | response.to = message.frm
536 | else:
537 | response.to = (
538 | message.frm.room
539 | if isinstance(message.frm, RoomOccupant)
540 | else message.frm
541 | )
542 |
543 | if threaded:
544 | response.extras["root_id"] = message.extras.get("root_id")
545 | self.driver.posts.get_post(message.extras.get("root_id"))
546 | response.parent = message
547 |
548 | return response
549 |
550 | def get_public_channels(self):
551 | channels = []
552 | page = 0
553 | channel_page_limit = 200
554 | while True:
555 | channel_list = self.driver.channels.get_public_channels(
556 | team_id=self.teamid,
557 | params={"page": page, "per_page": channel_page_limit},
558 | )
559 | if len(channel_list) == 0:
560 | break
561 | else:
562 | channels.extend(channel_list)
563 | page += 1
564 | return channels
565 |
566 | def channels(self, joined_only=False):
567 | channels = []
568 | channels.extend(
569 | self.driver.channels.get_channels_for_user(
570 | user_id=self.userid, team_id=self.teamid
571 | )
572 | )
573 | if not joined_only:
574 | public_channels = self.get_public_channels()
575 | for channel in public_channels:
576 | if channel not in channels:
577 | channels.append(channel)
578 | return channels
579 |
580 | def rooms(self):
581 | """Return public and private channels, but no direct channels"""
582 | rooms = self.channels(joined_only=True)
583 | channels = [channel for channel in rooms if channel["type"] != "D"]
584 | return [
585 | MattermostRoom(channelid=channel["id"], teamid=channel["team_id"], bot=self)
586 | for channel in channels
587 | ]
588 |
589 | def channelid_to_channelname(self, channelid):
590 | """Convert the channelid in the current team to the channel name"""
591 | channel = self.driver.channels.get_channel(channel_id=channelid)
592 | if "name" not in channel:
593 | raise RoomDoesNotExistError(
594 | "No channel with ID {} exists in team with ID {}".format(
595 | id, self.teamid
596 | )
597 | )
598 | return channel["name"]
599 |
600 | def channelname_to_channelid(self, name):
601 | """Convert the channelname in the current team to the channel id"""
602 | channel = self.driver.channels.get_channel_by_name(
603 | team_id=self.teamid, channel_name=name
604 | )
605 | if "id" not in channel:
606 | raise RoomDoesNotExistError(
607 | "No channel with name {} exists in team with ID {}".format(
608 | name, self.teamid
609 | )
610 | )
611 | return channel["id"]
612 |
613 | def __hash__(self):
614 | return 0 # This is a singleton anyway
615 |
--------------------------------------------------------------------------------
/src/err-backend-mattermost/mattermostlib/mattermostPerson.py:
--------------------------------------------------------------------------------
1 | import logging
2 |
3 | from errbot.backends.base import Person
4 |
5 | log = logging.getLogger("errbot.backends.mattermost.person")
6 |
7 |
8 | class MattermostPerson(Person):
9 | """
10 | A Person in Mattermost
11 | """
12 |
13 | def __init__(self, driver, userid=None, channelid=None, teamid=None):
14 | self._userid = userid
15 | self._channelid = channelid
16 | self._teamid = teamid
17 | self._driver = driver
18 |
19 | # caching attributes in order to prevent excessive http requests
20 | self._username = None # initialized if self.username called at least once
21 | self._fullname = None # initialized if self.fullname called at least once
22 | self._email = None # initialized if self.email called at least once
23 |
24 | @property
25 | def userid(self) -> str:
26 | return self._userid
27 |
28 | @property
29 | def username(self) -> str:
30 | if self._username is None:
31 | self._username = self.get_username()
32 | return self._username
33 |
34 | def get_username(self) -> str:
35 | user = self._driver.users.get_user(user_id=self.userid)
36 | if "username" not in user:
37 | log.error("Can't find username for user with ID {}".format(self._userid))
38 | return "<{}>".format(self._userid)
39 | return user["username"]
40 |
41 | @property
42 | def email(self) -> str:
43 | if self._email is None:
44 | self._email = self.get_email()
45 | return self._email
46 |
47 | def get_email(self) -> str:
48 | user = self._driver.users.get_user(user_id=self.userid)
49 | return user.get("email", "")
50 |
51 | @property
52 | def teamid(self) -> str:
53 | return self._teamid
54 |
55 | @property
56 | def channelid(self) -> str:
57 | return self._channelid
58 |
59 | @property
60 | def nick(self) -> str:
61 | return self.username
62 |
63 | @property
64 | def client(self) -> str:
65 | return self._channelid
66 |
67 | @property
68 | def domain(self) -> str:
69 | return self._driver.client.url
70 |
71 | @property
72 | def fullname(self) -> str:
73 | if self._fullname is None:
74 | self._fullname = self.get_fullname()
75 | return self._fullname
76 |
77 | def get_fullname(self):
78 | user = self._driver.users.get_user(user_id=self.userid)
79 |
80 | fullname = user.get("first_name", "")
81 | if fullname == "":
82 | log.warning("No first name for user with ID {}".format(self._userid))
83 |
84 | fullname += " {}".format(user.get("last_name", ""))
85 | if fullname == "{} ".format(user.get("first_name", "")):
86 | log.warning("No surname for user with ID {}".format(self._userid))
87 | fullname.strip()
88 |
89 | return f"{fullname}"
90 |
91 | @property
92 | def person(self):
93 | return "@{}".format(self.username)
94 |
95 | @property
96 | def aclattr(self):
97 | return "@{}".format(self.username)
98 |
99 | def __unicode__(self):
100 | return "@{}".format(self.username)
101 |
102 | def __str__(self):
103 | return self.__unicode__()
104 |
105 | def __eq__(self, other):
106 | if not isinstance(other, MattermostPerson):
107 | log.warning("Tried to compare a MattermostPerson with a %s", type(other))
108 | return False
109 | return other.userid == self.userid
110 |
--------------------------------------------------------------------------------
/src/err-backend-mattermost/mattermostlib/mattermostRoom.py:
--------------------------------------------------------------------------------
1 | import logging
2 | from errbot.backends.base import (
3 | Room,
4 | RoomDoesNotExistError,
5 | RoomError,
6 | UserDoesNotExistError,
7 | )
8 | from mattermostdriver.exceptions import (
9 | NotEnoughPermissions,
10 | ResourceNotFound,
11 | InvalidOrMissingParameters,
12 | )
13 | from .mattermostRoomOccupant import MattermostRoomOccupant
14 |
15 | log = logging.getLogger("errbot.backends.mattermost.room")
16 |
17 |
18 | class MattermostRoom(Room):
19 | def __init__(self, name=None, channelid=None, teamid=None, bot=None):
20 | if channelid is not None and name is not None:
21 | raise ValueError("channelid and name are mutually exclusive")
22 | if teamid is None:
23 | raise ValueError("teamid is not optional")
24 |
25 | if name is not None:
26 | if name.startswith("~"):
27 | self._name = name[1:]
28 | else:
29 | self._name = name
30 | else:
31 | self._name = bot.channelid_to_channelname(channelid)
32 |
33 | self._teamid = teamid
34 | self._id = None if channelid is None else channelid
35 | if self._id is None and name is not None:
36 | try:
37 | self._id = bot.channelname_to_channelid(name)
38 | except RoomDoesNotExistError as e:
39 | # If the room does not exist, maybe it will be created.
40 | log.info(e)
41 | self._bot = bot
42 | self.driver = bot.driver
43 |
44 | @property
45 | def teamid(self):
46 | return self._teamid
47 |
48 | @property
49 | def name(self):
50 | return self._name
51 |
52 | @property
53 | def id(self):
54 | if self._id is None:
55 | self._id = self._channel["id"]
56 | return self._id
57 |
58 | @property
59 | def userid(self):
60 | return self._bot.userid
61 |
62 | @property
63 | def _channel(self):
64 | channel = self.driver.channels.get_channel_by_name(
65 | team_id=self.teamid, channel_name=self.name
66 | )
67 | if "status_code" in channel and channel["status_code"] != 200:
68 | raise RoomDoesNotExistError(
69 | "{}: {}".format(channel["status_code"], channel["message"])
70 | )
71 | return channel
72 |
73 | @property
74 | def _channel_info(self):
75 | return NotImplementedError("TODO")
76 |
77 | @property
78 | def private(self):
79 | return self._channel.type == "P"
80 |
81 | @property
82 | def exists(self):
83 | channels = []
84 | channels.extend(
85 | self.driver.channels.get_channels_for_user(
86 | user_id="me", team_id=self.teamid
87 | )
88 | )
89 | public_channels = self._bot.get_public_channels()
90 | for channel in public_channels:
91 | if channel not in channels:
92 | channels.append(channel)
93 | return len([c for c in channels if c["name"] == self.name]) > 0
94 |
95 | @property
96 | def joined(self):
97 | channels = self.driver.channels.get_channels_for_user(
98 | user_id="me", team_id=self.teamid
99 | )
100 | return len([c for c in channels if c["name"] == self.name]) > 0
101 |
102 | @property
103 | def topic(self):
104 | if self._channel["header"] == "":
105 | return None
106 | else:
107 | return self._channel["header"]
108 |
109 | @topic.setter
110 | def topic(self, topic):
111 | self.driver.channels.update_channel(
112 | channel_id=self.id, options={"header": topic, "id": self.id}
113 | )
114 |
115 | @property
116 | def purpose(self):
117 | if self._channel["purpose"] == "":
118 | return None
119 | else:
120 | return self._channel["purpose"]
121 |
122 | @purpose.setter
123 | def purpose(self, purpose):
124 | self.driver.channels.update_channel(
125 | channel_id=self.id, options={"purpose": purpose, "id": self.id}
126 | )
127 |
128 | @property
129 | def occupants(self):
130 | member_count = self.driver.channels.get_channel_statistics(channel_id=self.id)[
131 | "member_count"
132 | ]
133 | members = []
134 | user_page_limit = 200
135 | for start in range(0, member_count, user_page_limit):
136 | member_part = self.driver.channels.get_channel_members(
137 | channel_id=self.id, params={"page": start, "per_page": user_page_limit}
138 | )
139 | members.extend(member_part)
140 |
141 | room_occupants = [
142 | MattermostRoomOccupant(
143 | self.driver,
144 | userid=m["user_id"],
145 | teamid=self.teamid,
146 | channelid=self.id,
147 | bot=self._bot,
148 | )
149 | for m in members
150 | ]
151 | return room_occupants
152 |
153 | def create(self, private=False):
154 | channel_type = "O"
155 | if private:
156 | log.info("Creating private group {}".format(str(self)))
157 | channel_type = "P"
158 | else:
159 | log.info("Creating public channel {}".format(str(self)))
160 | try:
161 | self.driver.channels.create_channel(
162 | options={
163 | "team_id": self.teamid,
164 | "name": self.name,
165 | "display_name": self.name,
166 | "type": channel_type,
167 | }
168 | )
169 | self.driver.channels.get_channel_by_name(
170 | team_id=self.teamid, channel_name=self.name
171 | )
172 | self._bot.callback_room_joined(self)
173 | except (NotEnoughPermissions, ResourceNotFound) as e:
174 | raise RoomError(e)
175 |
176 | def join(self, username: str = None, password: str = None):
177 | if not self.exists:
178 | log.info(
179 | "Channel {} doesn't seem exist, trying to create it.".format(str(self))
180 | )
181 | self.create() # This always creates a public room!
182 | log.info("Joining channel {} ({})".format(str(self), self.id))
183 | try:
184 | self.driver.channels.add_user(
185 | channel_id=self._id, options={"user_id": self.userid}
186 | )
187 | self._bot.callback_room_joined(self)
188 | except (InvalidOrMissingParameters, NotEnoughPermissions) as e:
189 | raise RoomError(e)
190 |
191 | def leave(self, reason: str = None):
192 | log.info("Leaving channel {} ({})".format(str(self), self.id))
193 | try:
194 | self.driver.channels.remove_channel_member(
195 | channel_id=self.id, user_id=self.userid
196 | )
197 | self._bot.callback_room_left(self)
198 | except (InvalidOrMissingParameters, NotEnoughPermissions) as e:
199 | raise RoomError(e)
200 |
201 | def destroy(self):
202 | try:
203 | self.driver.channels.delete_channel(channel_id=self.id)
204 | self._bot.callback_room_left(self)
205 | except (InvalidOrMissingParameters, NotEnoughPermissions) as e:
206 | log.debug("Could not delete the channel. Are you a member of the channel?")
207 | raise RoomError(e)
208 | self._id = None
209 |
210 | def invite(self, *args):
211 | user_count = self.driver.teams.get_team_stats(team_id=self.teamid)[
212 | "total_member_count"
213 | ]
214 | user_page_limit = 200
215 | users_not_in_channel = []
216 | for start in range(0, user_count, user_page_limit):
217 | users_not_in_channel.extend(
218 | self.driver.users.get_users(
219 | params={
220 | "page": start,
221 | "per_page": user_page_limit,
222 | "in_team": self.teamid,
223 | "not_in_channel": self.id,
224 | }
225 | )
226 | )
227 | users = {}
228 | for user in users_not_in_channel:
229 | users.update({user["username"]: user["id"]})
230 | for user in args:
231 | if user not in users:
232 | raise UserDoesNotExistError("User '{}' not found".format(user))
233 | log.info("Inviting {} into {} ({})".format(user, str(self), self.id))
234 |
235 | try:
236 | self.driver.channels.add_user(
237 | channel_id=self.id, options={"user_id": users[user]}
238 | )
239 | except (InvalidOrMissingParameters, NotEnoughPermissions):
240 | raise RoomError(
241 | "Unable to invite {} to channel {} ({})".format(
242 | user, str(self), self.id
243 | )
244 | )
245 |
246 | def __str__(self):
247 | return "~{}".format(self._name)
248 |
249 | def __eq__(self, other):
250 | if not isinstance(other, MattermostRoom):
251 | return False
252 | return self.id == other.id
253 |
--------------------------------------------------------------------------------
/src/err-backend-mattermost/mattermostlib/mattermostRoomOccupant.py:
--------------------------------------------------------------------------------
1 | import logging
2 | from errbot.backends.base import RoomOccupant
3 | from .mattermostPerson import MattermostPerson
4 |
5 | log = logging.getLogger("errbot.backends.mattermost.roomOccupant")
6 |
7 |
8 | class MattermostRoomOccupant(RoomOccupant, MattermostPerson):
9 | """
10 | A Person inside a Team (Room)
11 | """
12 |
13 | def __init__(self, client, teamid, userid, channelid, bot):
14 | super().__init__(client, userid, channelid)
15 | self._teamid = teamid
16 | # Importing inside __init__ to prevent a circular import, which is ugly
17 | from .mattermostRoom import MattermostRoom
18 |
19 | self._room = MattermostRoom(channelid=channelid, teamid=teamid, bot=bot)
20 |
21 | @property
22 | def room(self):
23 | return self._room
24 |
25 | def __unicode__(self):
26 | return "~{}/{}".format(self._room.name, self.username)
27 |
28 | def __str__(self):
29 | return self.__unicode__()
30 |
31 | def __eq__(self, other):
32 | if not isinstance(other, RoomOccupant):
33 | log.warning(
34 | "tried to compare a MattermostRoomOccupant with"
35 | f" a MattermostPerson {self} vs {other}"
36 | )
37 | return False
38 | return other.room.id == self.room.id and other.userid == self.userid
39 |
--------------------------------------------------------------------------------
/tests/config.py:
--------------------------------------------------------------------------------
1 | ##########################################################################
2 | # #
3 | # This is the config-template for Err. This file should be copied and #
4 | # renamed to config.py, then modified as you see fit to run Errbot #
5 | # the way you like it. #
6 | # #
7 | # As this is a regular Python file, note that you can do variable #
8 | # assignments and the likes as usual. This can be useful for example if #
9 | # you use the same values in multiple places. #
10 | # #
11 | # Note: Various config options require a tuple to be specified, even #
12 | # when you are configuring only a single value. An example of this is #
13 | # the BOT_ADMINS option. Make sure you use a valid tuple here, even if #
14 | # you are only configuring a single item, else you will get errors. #
15 | # (So don't forget the trailing ',' in these cases) #
16 | # #
17 | ##########################################################################
18 |
19 | import logging
20 | import os
21 |
22 | local_dir_path = os.path.dirname(__file__)
23 |
24 | ##########################################################################
25 | # Core Errbot configuration #
26 | ##########################################################################
27 |
28 | BACKEND = "Mattermost"
29 | BOT_EXTRA_BACKEND_DIR = os.path.join(local_dir_path, "..")
30 |
31 | BOT_ADMINS = "@gpr" # Names need the @ in front!
32 | BOT_IDENTITY = {
33 | # Required
34 | "team": "default",
35 | "server": "0.0.0.0",
36 | # For the login, either
37 | "login": "errbot",
38 | "password": "errbot",
39 | # Optional
40 | "insecure": True, # Default = False. Set to true for self signed certificates
41 | "scheme": "http", # Default = https
42 | "port": 8080, # Default = 8065
43 | "timeout": 30, # Default = 30. If the webserver disconnects idle connections later/earlier change this value
44 | "cards_hook": "osjx5d4ijfft58pf4tyci79jhh", # Needed for cards/attachments
45 | }
46 |
47 | STORAGE = "Memory"
48 | BOT_DATA_DIR = os.path.join(local_dir_path, "data")
49 | BOT_EXTRA_PLUGIN_DIR = os.path.join(local_dir_path, "plugins")
50 | PLUGINS_CALLBACK_ORDER = (None,)
51 | AUTOINSTALL_DEPS = True
52 | BOT_LOG_FILE = BOT_DATA_DIR + "/err.log"
53 | BOT_LOG_LEVEL = logging.DEBUG
54 | BOT_LOG_SENTRY = False
55 | SENTRY_DSN = ""
56 | SENTRY_LOGLEVEL = BOT_LOG_LEVEL
57 | BOT_ASYNC = False
58 | BOT_ADMINS_NOTIFICATIONS = "@gpr"
59 | BOT_PREFIX = "!"
60 |
61 | # BOT_PREFIX_OPTIONAL_ON_CHAT = False
62 | # BOT_ALT_PREFIXES = ('Err',)
63 | # BOT_ALT_PREFIX_SEPARATORS = (':', ',', ';')
64 | # BOT_ALT_PREFIX_CASEINSENSITIVE = True
65 | # HIDE_RESTRICTED_COMMANDS = False
66 | # HIDE_RESTRICTED_ACCESS = False
67 |
68 | # A list of commands which should be responded to in private, even if
69 | # the command was given in a MUC. For example:
70 | # DIVERT_TO_PRIVATE = ('help', 'about', 'status')
71 | DIVERT_TO_PRIVATE = ("status", "help", "about")
72 |
73 | # A list of commands which should be responded to in a thread if the backend supports it.
74 | # For example:
75 | # DIVERT_TO_THREAD = ('help', 'about', 'status')
76 | DIVERT_TO_THREAD = "divert_to_thread"
77 |
78 | # Chat relay
79 | # Can be used to relay one to one message from specific users to the bot
80 | # to MUCs. This can be useful with XMPP notifiers like for example the
81 | # standard Altassian Jira which don't have native support for MUC.
82 | # For example: CHATROOM_RELAY = {'gbin@localhost' : (_TEST_ROOM,)}
83 | CHATROOM_RELAY = {}
84 |
85 | # Reverse chat relay
86 | # This feature forwards whatever is said to a specific user.
87 | # It can be useful if you client like gtalk doesn't support MUC correctly
88 | # For example: REVERSE_CHATROOM_RELAY = {_TEST_ROOM : ('gbin@localhost',)}
89 | REVERSE_CHATROOM_RELAY = {}
90 |
91 | # Allow messages sent in a chatroom to be directed at requester.
92 | # GROUPCHAT_NICK_PREFIXED = False
93 |
94 | # Disable table borders, making output more compact (supported only on IRC, Slack and Telegram currently).
95 | COMPACT_OUTPUT = True
96 |
97 | # Disables the logging output in Text mode and only outputs Ansi.
98 | # TEXT_DEMO_MODE = False
99 |
100 | # Prevent ErrBot from saying anything if the command is unrecognized.
101 | SUPPRESS_CMD_NOT_FOUND = False
102 |
--------------------------------------------------------------------------------
/tests/docker-compose.yml:
--------------------------------------------------------------------------------
1 | version: "2"
2 |
3 | services:
4 |
5 | db:
6 | image: mattermost/mattermost-prod-db
7 | environment:
8 | - POSTGRES_USER=mmuser
9 | - POSTGRES_PASSWORD=mmuser_password
10 | - POSTGRES_DB=mattermost
11 |
12 | app:
13 | image: mattermost/mattermost-prod-app
14 | environment:
15 | - MM_USERNAME=mmuser
16 | - MM_PASSWORD=mmuser_password
17 | - MM_DBNAME=mattermost
18 |
19 | web:
20 | image: mattermost/mattermost-prod-web
21 | ports:
22 | - "8080:80"
23 | - "8443:443"
--------------------------------------------------------------------------------
/tests/init_mattermost.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | docker-compose up -d
4 |
5 | # Wait for Mattermost
6 | sleep 5
7 |
8 | docker-compose exec platform user create --email errbot@example.com --username errbot --password errbot
9 | docker-compose exec platform user verify errbot
--------------------------------------------------------------------------------
/tests/plugins/test.plug:
--------------------------------------------------------------------------------
1 | [Core]
2 | Name = TestPlugin
3 | Module = test
4 |
5 | [Documentation]
6 | Description = A Test plugin
7 |
8 | [Python]
9 | Version = 3
--------------------------------------------------------------------------------
/tests/plugins/test.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | from errbot import BotPlugin, botcmd, webhook
4 | import re
5 |
6 |
7 | class TestPlugin(BotPlugin):
8 | """
9 | Fill in your plugin description here.
10 | """
11 |
12 | def activate(self):
13 | """
14 | Triggers on plugin activation
15 |
16 | You should delete it if you're not using it to override any default behaviour
17 | """
18 | super(TestPlugin, self).activate()
19 |
20 | def deactivate(self):
21 | """
22 | Triggers on plugin deactivation
23 |
24 | You should delete it if you're not using it to override any default behaviour
25 | """
26 | super(TestPlugin, self).deactivate()
27 |
28 | def get_configuration_template(self):
29 | """
30 | Defines the configuration structure this plugin supports
31 |
32 | You should delete it if your plugin doesn't use any configuration like this
33 | """
34 | return {"EXAMPLE_KEY_1": "Example value", "EXAMPLE_KEY_2": ["Example", "Value"]}
35 |
36 | def check_configuration(self, configuration):
37 | """
38 | Triggers when the configuration is checked, shortly before activation
39 |
40 | You should delete it if you're not using it to override any default behaviour
41 | """
42 | super(TestPlugin, self).check_configuration()
43 |
44 | def callback_connect(self):
45 | """
46 | Triggers when bot is connected
47 |
48 | You should delete it if you're not using it to override any default behaviour
49 | """
50 |
51 | pass
52 |
53 | def callback_message(self, message):
54 | """
55 | Triggered for every received message that isn't coming from the bot itself
56 |
57 | You should delete it if you're not using it to override any default behaviour
58 | """
59 | if re.compile("^!.*$").match(message.body):
60 | pass
61 |
62 | # Threaded message
63 | self.send(
64 | in_reply_to=message,
65 | identifier=message.to,
66 | text="Call back threaded message",
67 | )
68 |
69 | # Single message
70 | self.send(identifier=message.to, text="Call back single message")
71 |
72 | #
73 | self.send(identifier=message.frm, text="Call back 1to1 message")
74 |
75 | pass
76 |
77 | def callback_botmessage(self, message):
78 | """
79 | Triggered for every message that comes from the bot itself
80 |
81 | You should delete it if you're not using it to override any default behaviour
82 | """
83 | pass
84 |
85 | @webhook
86 | def example_webhook(self, incoming_request):
87 | """A webhook which simply returns 'Example'"""
88 | return "Example"
89 |
90 | # Passing split_args_with=None will cause arguments to be split on any kind
91 | # of whitespace, just like Python's split() does
92 | @botcmd(split_args_with=None)
93 | def example(self, mess, args):
94 | """A command which simply returns 'Example'"""
95 | return "This message SHOULD NOT have created a thread"
96 |
97 | # Passing split_args_with=None will cause arguments to be split on any kind
98 | # of whitespace, just like Python's split() does
99 | @botcmd(split_args_with=None)
100 | def divert_to_thread(self, mess, args):
101 | """A command which simply returns 'Example'"""
102 | return "This message SHOULD have created a thread"
103 |
--------------------------------------------------------------------------------
/tests/requirements.txt:
--------------------------------------------------------------------------------
1 | autopep8
2 | errbot
--------------------------------------------------------------------------------