├── bot ├── __init__.py └── bot.py ├── gl ├── __init__.py ├── settings.py └── utils.py ├── opt_requirements.txt ├── requirements.txt ├── .gitmodules ├── scripts ├── clean.sh ├── generate-authors.sh ├── generate-plugins-table.py └── create_base_plugin.py ├── plugins ├── __init__.py ├── echo.py ├── clever.py ├── download_media.py ├── calc.py ├── id.py ├── channels.py ├── help.py ├── media.py ├── money.py ├── imgtosticker.py └── plugins.py ├── examples ├── echo.py └── stateful.py ├── AUTHORS ├── .travis.yml ├── .gitignore ├── mock └── tgl.py ├── tests.py ├── CONTRIBUTING.md ├── launch.sh ├── README.md └── LICENSE /bot/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /gl/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /opt_requirements.txt: -------------------------------------------------------------------------------- 1 | pillow 2 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | cleverbot2 2 | six 3 | requests 4 | progressbar2 5 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "tg"] 2 | path = tg 3 | url = https://github.com/vysheng/tg 4 | -------------------------------------------------------------------------------- /scripts/clean.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | find . -type f -name '*.pyc' -delete 3 | find . -type d -name '__pycache__' -delete 4 | -------------------------------------------------------------------------------- /plugins/__init__.py: -------------------------------------------------------------------------------- 1 | # import os 2 | # import glob 3 | # modules = glob.glob(os.path.dirname(__file__) + "/*.py") 4 | # __all__ = [os.path.basename(f)[:-3] for f in modules] 5 | -------------------------------------------------------------------------------- /gl/settings.py: -------------------------------------------------------------------------------- 1 | 2 | # Global variables 3 | 4 | DEBUG = False 5 | 6 | PLUGINS = {} 7 | ALL_PLUGINS = set() 8 | ENABLED_PLUGINS = set() 9 | DISABLED_PLUGINS_ON_CHAT = {} 10 | SUDO_USERS = set() 11 | DISABLED_CHANNELS = set() 12 | OUR_ID = 0 13 | -------------------------------------------------------------------------------- /plugins/echo.py: -------------------------------------------------------------------------------- 1 | def run(msg, matches): 2 | text = matches[0].strip().lstrip('!') 3 | return text 4 | 5 | 6 | __info__ = { 7 | "description": "Simplest plugin ever!", 8 | "usage": ["!echo (text)"], 9 | "patterns": [ 10 | "^!echo +(.+)$", 11 | ], 12 | "run": run 13 | } 14 | -------------------------------------------------------------------------------- /examples/echo.py: -------------------------------------------------------------------------------- 1 | def run(msg, matches): 2 | text = matches[0].strip().lstrip('!') 3 | return text 4 | 5 | 6 | __info__ = { 7 | "description": "Simplest plugin and example :)", 8 | "usage": ["!echo (text)"], 9 | "patterns": [ 10 | "^!echo +(.+)$", 11 | ], 12 | "run": run 13 | } 14 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | # This file lists all individuals having contributed content to the repository. 2 | # For how it is generated, see `scripts/generate-authors.sh`. 3 | # The script is purely based in docker's one: https://github.com/docker/docker 4 | 5 | awkward_potato / Hasan 6 | Rock Neurotiko 7 | rockneurotiko 8 | -------------------------------------------------------------------------------- /plugins/clever.py: -------------------------------------------------------------------------------- 1 | import cleverbot 2 | 3 | 4 | def run(msg, matches): 5 | text = matches[0].strip().lstrip('!') 6 | # cb = cleverbot.Session() 7 | cb = cleverbot.Cleverbot() 8 | response = cb.ask(text) # Ask 9 | return response 10 | 11 | 12 | __info__ = { 13 | "description": "Cleverbot plugin.", 14 | "usage": ["!clever (text): Say the text to cleverbot and receive the answer"], 15 | "patterns": [ 16 | "^!clever +(.+)$", 17 | ], 18 | "run": run 19 | } 20 | -------------------------------------------------------------------------------- /examples/stateful.py: -------------------------------------------------------------------------------- 1 | class StatefulTest: 2 | stateful = False 3 | 4 | def run(self, msg, matches): 5 | print("state", self.stateful) 6 | text = "My internal state is: {}".format(self.stateful) 7 | self.stateful = not self.stateful 8 | return text 9 | 10 | 11 | _MyClass = StatefulTest() 12 | 13 | __info__ = { 14 | "description": "Just an example with a class", 15 | "usage": ["!testclass"], 16 | "patterns": ["^!testclass$"], 17 | "run": _MyClass.run 18 | } 19 | -------------------------------------------------------------------------------- /scripts/generate-authors.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | cd "$(dirname "$(readlink -f "$BASH_SOURCE")")/.." 5 | 6 | # see also ".mailmap" for how email addresses and names are deduplicated 7 | 8 | { 9 | cat <<-'EOH' 10 | # This file lists all individuals having contributed content to the repository. 11 | # For how it is generated, see `scripts/generate-authors.sh`. 12 | # The script is purely based in docker's one: https://github.com/docker/docker 13 | EOH 14 | echo 15 | git log --format='%aN <%aE>' | LC_ALL=C.UTF-8 sort -uf 16 | } > AUTHORS 17 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "3.4" 4 | 5 | before_install: 6 | - sudo apt-get update -qq 7 | - sudo apt-get install libreadline-dev libconfig-dev libssl-dev lua5.2 liblua5.2-dev libevent-dev libjansson-dev python-dev make python-pip python3 python3-dev 8 | - sudo pip install virtualenv 9 | - sudo apt-get install libtiff4-dev libjpeg8-dev zlib1g-dev libfreetype6-dev liblcms1-dev libwebp-dev 10 | - ./launch.sh install 11 | - ./launch.sh optdeps 12 | 13 | install: 14 | - "pip install -r requirements.txt" 15 | - "pip install -r opt_requirements.txt" 16 | 17 | script: 18 | - python tests.py 19 | -------------------------------------------------------------------------------- /plugins/download_media.py: -------------------------------------------------------------------------------- 1 | def ppath(success, path): 2 | # Move to a user location? 3 | if success: 4 | print("File downloaded to: {}".format(path)) 5 | 6 | 7 | def run(msg, matches): 8 | if hasattr(msg, "load_{}".format(matches[0])): 9 | f = getattr(msg, "load_{}".format(matches[0])) 10 | f(ppath) 11 | 12 | 13 | __info__ = { 14 | "description": "When bot receives a media msg, download the media to the file system.", 15 | "usage": ["This plugin is automatic when someone send a file."], 16 | "patterns": [ 17 | "^\[(photo)\]$", 18 | "^\[(video)\]$", 19 | "^\[(video)_thumb\]$", 20 | "^\[(audio)\]$", 21 | "^\[(document)\]$", 22 | "^\[(document_thumb)\]$"], 23 | "run": run 24 | } 25 | -------------------------------------------------------------------------------- /plugins/calc.py: -------------------------------------------------------------------------------- 1 | from gl import utils 2 | 3 | 4 | def cb(r, receiver): 5 | text = r.text if r.text else 'An error occurred.' 6 | receiver.send_msg(text) 7 | 8 | 9 | def run(msg, matches): 10 | receiver = utils.get_receiver(msg) 11 | exp = matches[0] 12 | path = "http://api.mathjs.org/v1/" 13 | payload = {'expr': exp} 14 | if len(matches) > 1: 15 | payload.update({'precision': matches[1]}) 16 | gcb = utils.gac(cb, receiver) 17 | utils.mp_requests('GET', path, gcb, params=payload) 18 | 19 | __info__ = { 20 | "description": "A calculator to evaluate expressions", 21 | "usage": ["!calc (expression)"], 22 | "patterns": [ 23 | "^!calc ([\s\S]+) prec (\d+)?$", 24 | "^!calc ([\s\S]+)$"], 25 | "run": run 26 | } 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # pybotgram 2 | data/ 3 | 4 | # Byte-compiled / optimized / DLL files 5 | __pycache__/ 6 | *.py[cod] 7 | 8 | # C extensions 9 | *.so 10 | 11 | # Distribution / packaging 12 | .Python 13 | env/ 14 | build/ 15 | develop-eggs/ 16 | dist/ 17 | downloads/ 18 | eggs/ 19 | .eggs/ 20 | lib/ 21 | lib64/ 22 | parts/ 23 | sdist/ 24 | var/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .coverage 43 | .coverage.* 44 | .cache 45 | nosetests.xml 46 | coverage.xml 47 | *,cover 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | 56 | # Sphinx documentation 57 | docs/_build/ 58 | 59 | # PyBuilder 60 | target/ 61 | -------------------------------------------------------------------------------- /mock/tgl.py: -------------------------------------------------------------------------------- 1 | # Test runner for tgl module in python 2 | 3 | on_binlog_replay_end_cb = None 4 | on_get_difference_end_cb = None 5 | on_our_id_cb = None 6 | on_msg_receive_cb = None 7 | on_secret_chat_update_cb = None 8 | on_user_update_cb = None 9 | on_chat_update_cb = None 10 | 11 | 12 | def set_on_binlog_replay_end(on_binlog_replay_end): 13 | global on_binlog_replay_end_cb 14 | on_binlog_replay_end_cb = on_binlog_replay_end 15 | 16 | 17 | def set_on_get_difference_end(on_get_difference_end): 18 | global on_get_difference_end_cb 19 | on_get_difference_end_cb = on_get_difference_end 20 | 21 | 22 | def set_on_our_id(on_our_id): 23 | global on_our_id_cb 24 | on_our_id_cb = on_our_id 25 | 26 | 27 | def set_on_msg_receive(on_msg_receive): 28 | global on_msg_receive_cb 29 | on_msg_receive_cb = on_msg_receive 30 | 31 | 32 | def set_on_secret_chat_update(on_secret_chat_update): 33 | global on_secret_chat_update_cb 34 | on_secret_chat_update_cb = on_secret_chat_update 35 | 36 | 37 | def set_on_user_update(on_user_update): 38 | global on_user_update_cb 39 | on_user_update_cb = on_user_update 40 | 41 | 42 | def set_on_chat_update(on_chat_update): 43 | global on_chat_update_cb 44 | on_chat_update_cb = on_chat_update 45 | 46 | 47 | def send_msg(peer_type, peer_id, msg): 48 | print("type: {0}, id: {1} msg:\n{2}".format(peer_type, peer_id, msg)) 49 | 50 | 51 | def mark_read(peer_type, peer_id, cb): 52 | pass 53 | -------------------------------------------------------------------------------- /plugins/id.py: -------------------------------------------------------------------------------- 1 | from gl import utils 2 | 3 | 4 | def user_id(msg): 5 | text = "{} (user#id{})".format(msg.src.name, msg.src.id) 6 | if utils.is_chat_msg(msg): 7 | text = "{}\nYou are in group {} (chat#id{})".format(text, msg.dest.name, msg.dest.id) 8 | return text 9 | 10 | 11 | def callback(succ, peer): 12 | text = "IDs for chat {} (chat#id{}) [for now only the id]\nThere are {} members\n--------".format(peer.name, peer.id, len(peer.user_list)) 13 | for p in peer.user_list: 14 | text = "{}\n{}".format(text, p) 15 | peer.send_msg(text) 16 | 17 | 18 | def run(msg, matches): 19 | receiver = utils.get_receiver(msg) 20 | print() 21 | if len(matches) == 1: 22 | if matches[0] == "!id": 23 | return user_id(msg) 24 | elif matches[0] == 'chat': 25 | if not utils.is_chat_msg(msg): 26 | return 'You are not in a chat' 27 | else: 28 | receiver.info(callback) 29 | elif len(matches) == 2: 30 | return "Not implemented yet the function necesary in tgl :'('" 31 | # Implement your run function here 32 | return "" 33 | 34 | __info__ = { 35 | "description": [ 36 | "This plugin will return your id or the ids of the people in a chat"], 37 | "usage": [ 38 | "!id: Return your ID and the chat id if you are in one.", 39 | "!ids chat: Return the IDs of the current chat members.", 40 | "!ids chat (id): Return the IDs of the chat (id) members."], 41 | "patterns": [ 42 | "^!id$", 43 | # "^!ids? (chat) (\d+)$", 44 | "^!ids? (chat)$"], 45 | "run": run, 46 | "privileged": False 47 | } 48 | -------------------------------------------------------------------------------- /tests.py: -------------------------------------------------------------------------------- 1 | import importlib 2 | import shutil 3 | import os 4 | # Copy the mock and import it 5 | if os.path.isfile('tgl.pyc'): 6 | shutil.os.remove('tgl.pyc') 7 | shutil.copy('mock/tgl.py', '.') 8 | import tgl 9 | from gl import settings 10 | from gl import utils 11 | 12 | 13 | def print_error(msg, plugin): 14 | print('\033[31mError in plugin \033[93m"{}"\033[39m'.format(plugin)) 15 | print('\033[31mMessage: {}\033[39m'.format(msg)) 16 | 17 | 18 | def check_plugins(): 19 | # Check the plugins 20 | res = 0 21 | for p in utils.clean_plugins(utils.get_all_plugins()): 22 | try: 23 | m = importlib.import_module('plugins.{}'.format(p)) 24 | if not hasattr(m, '__info__'): 25 | print_error("Don't have __info__", p) 26 | res = 1 27 | if type(m.__info__) is not dict: 28 | print_error("__info__ is not a dictionary.", p) 29 | res = 1 30 | info = m.__info__ 31 | haverun = hasattr(info.get("run"), '__call__') 32 | havecron = hasattr(info.get("cron"), '__call__') 33 | haveprec = hasattr(info.get("pre_process"), '__call__') 34 | if not (haverun or havecron or haveprec): 35 | print_error("Every plugin need a run, cron or pre_process function, and this does't have any of that.", p) 36 | res = 1 37 | except Exception as e: 38 | print('\033[31mError loading plugin {}\033[39m'.format(p)) 39 | print('\033[31m{}\033[39m'.format(e)) 40 | res = 1 41 | return res 42 | 43 | res = check_plugins() 44 | if os.path.isfile('tgl.pyc'): 45 | shutil.os.remove('tgl.pyc') 46 | shutil.os.remove('./tgl.py') 47 | 48 | exit(res) 49 | -------------------------------------------------------------------------------- /plugins/channels.py: -------------------------------------------------------------------------------- 1 | from gl import utils 2 | 3 | 4 | def enable_channel(receiver): 5 | conf = utils.get_safe_setting('disabled_channels', list) 6 | if receiver not in conf: 7 | return "Channel is not disabled!" 8 | utils.generic_cfg(receiver, 'remove', list, 'disabled_channels') 9 | utils.reload_cfg_plugins('disabled_channels') 10 | return "Channel enabled" 11 | 12 | 13 | def disable_channel(receiver): 14 | conf = utils.get_safe_setting('disabled_channels', list) 15 | if receiver in conf: 16 | return "Channel already disabled!" 17 | utils.generic_cfg(receiver, 'append', list, 'disabled_channels') 18 | utils.reload_cfg_plugins('disabled_channels') 19 | return "Channel disabled" 20 | 21 | 22 | def run(msg, matches): 23 | receiver = utils.get_receiver_id(msg) 24 | if matches[0] == "enable": 25 | return enable_channel(receiver) 26 | if matches[0] == "disable": 27 | return disable_channel(receiver) 28 | 29 | 30 | def pre_process(msg): 31 | receiver = utils.get_receiver_id(msg) 32 | if utils.is_sudo(msg) and msg.text == "!channel enable": 33 | peer = utils.get_receiver(msg) 34 | enable_channel(receiver) 35 | peer.send_msg("Channel enabled") 36 | return None # Already processed 37 | conf = utils.get_safe_setting('disabled_channels', list) 38 | if receiver in conf: 39 | return None # Don't process the message 40 | return msg 41 | 42 | 43 | __info__ = { 44 | "description": ["Plugin to manage channels.", 45 | "Enable or disable channel."], 46 | "usage": ["!channel enable: enable current channel", 47 | "!channel disable: disable current channel"], 48 | "patterns": ["^!channel? (enable|disable)$"], 49 | "run": run, 50 | "privileged": True, 51 | "pre_process": pre_process 52 | } 53 | -------------------------------------------------------------------------------- /plugins/help.py: -------------------------------------------------------------------------------- 1 | from gl import settings 2 | from gl import utils 3 | import collections 4 | 5 | 6 | def gen_help(): 7 | text = "Plugin list:\n\n" 8 | for pname, p in settings.PLUGINS.items(): 9 | info = p.__info__ if hasattr(p, '__info__') else {} 10 | text += "{}: {}\n".format(pname, info.get('description') or 'No description') 11 | text += "\nWrite \"!help [plugin name]\" for more info.\nOr \"!help all\" to show all info." 12 | return text 13 | 14 | 15 | def help_plugin(name): 16 | if not utils.plugin_enabled(name): 17 | return "Plugin {} is not enabled, try execute \"!help\"".format(name) 18 | plg = settings.PLUGINS[name] 19 | if not hasattr(plg, '__info__'): 20 | return 'The plugin {} don\'t have information'.format(name) 21 | if not plg.__info__.get('usage'): 22 | return 'The plugin {} don\'t have usage info'.format(name) 23 | usage = plg.__info__['usage'] 24 | if type(usage) is str: 25 | return usage 26 | elif isinstance(usage, collections.Iterable): 27 | return '\n'.join(usage) 28 | return '' 29 | 30 | 31 | def help_all(): 32 | return '\n\n'.join(map(help_plugin, settings.ENABLED_PLUGINS)) 33 | 34 | 35 | def run(msg, matches): 36 | if len(matches) != 1: 37 | return 38 | if matches[0] == "!help": 39 | return gen_help() 40 | if matches[0] == "all": 41 | return help_all() 42 | return help_plugin(matches[0]) 43 | 44 | 45 | __info__ = { 46 | "description": ["Help plugin.", "Get info from other plugins."], 47 | "usage": ["!help: Show list of plugins.", 48 | "!help all: Show all commands for every plugin.", 49 | "!help [plugin name]: Commands for that plugin."], 50 | "patterns": [ 51 | "^!help$", 52 | "^!help ([\w_\.\-]+)$", 53 | ], 54 | "run": run 55 | # "cron": lambda: print(), 56 | # "pre_process": lambda x: print(x) 57 | } 58 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to pybotgram! 2 | 3 | If you are reading this, is because you want to help in the development of this project, and for that, we love you! 4 | 5 | In this file you will find some helpful guidelines if you want to understand how a plugin works, the posibilities, and more things! :-) 6 | 7 | ## Topics 8 | 9 | * [Previous considerations.](#previous-considerations) 10 | * [Installation.](#installation) 11 | * [Structure of a plugin.](#structure-of-a-plugin) 12 | * [Using the utils module.](#using-the-utils-module) 13 | * [Using the settings module.](#using-the-settings-module) 14 | 15 | 16 | ## Previous considerations 17 | 18 | The first thing that you need to know, is that the project and all the plugins have to be writed for `python 3.4`, there is no need to compatibility in your plugins with 2.7 :) 19 | 20 | Some operating systems have python3 as default python, like ArchLinux, but the majority still have python 2.7 as default, so, in the project we take some precautions. 21 | 22 | When you follow the [installation](#installation) instructions, you will install python3, pip3 and virtualenv3, this is necesary, because the installation also creates a python3 local environment. 23 | 24 | Virtualenv is a really great tool to have projects with their own dependencies isolated of the system and other projects, if you want to know more about this, check [virtualenv page](https://virtualenv.pypa.io/en/latest/) 25 | 26 | The only thing that you need to know, is that if you are going to develop, and not only execute `./launch.sh` for use the plugin, you will have to activate the environment while you are developing. 27 | 28 | After the installation, you need to have a directory called `env`. This is your environment! To activate it, type in the terminal: 29 | 30 | ``` 31 | source env/bin/activate 32 | ``` 33 | 34 | This will activate the environment in that terminal. Some shells give some hint to let you know if you are in a environment, for example, [zsh](http://www.zsh.org/) with [oh-my-zsh](https://github.com/robbyrussell/oh-my-zsh) give you this hint: 35 | 36 | IN DEVELOPMENT 37 | 38 | ## Installation 39 | 40 | First you will need to install succesfully the project, follow the instructions in the [Installation section of README.md](https://github.com/rockneurotiko/pybotgram#installation). 41 | 42 | ## Structure of a plugin 43 | 44 | IN DEVELOPMENT 45 | 46 | ## Using the utils module 47 | 48 | IN DEVELOPMENT 49 | 50 | ## Using the settings module 51 | -------------------------------------------------------------------------------- /plugins/media.py: -------------------------------------------------------------------------------- 1 | import mimetypes 2 | import tgl 3 | from gl import utils 4 | 5 | 6 | def async_callback_download(path, ext, receiver): 7 | if path is None: 8 | return 9 | mimetype, _ = mimetypes.guess_type(path) 10 | if not mimetype: 11 | return 12 | mime = mimetype.split('/')[0] 13 | f = tgl.send_file 14 | if ext == "gif" or ext == "webp" or mime == "text": 15 | f = tgl.send_document 16 | elif mime == "image": 17 | f = tgl.send_image 18 | elif mime == "audio": 19 | f = tgl.send_audio 20 | elif mime == "video": 21 | f = tgl.send_video 22 | print("Sending file with mime {} from path {}".format(mimetype, path)) 23 | f(receiver, path, utils.cb_rmp(path)) 24 | 25 | 26 | def synchronous(url, ext, receiver): 27 | path = '' 28 | try: 29 | path = utils.download_to_file(url, ext) 30 | except: 31 | print("Error downloading {}".format(url)) 32 | return 33 | mimetype, _ = mimetypes.guess_type(path) 34 | if not mimetype: 35 | return 36 | mime = mimetype.split('/')[0] 37 | f = tgl.send_file 38 | if ext == "gif" or ext == "webp" or mime == "text": 39 | f = tgl.send_document 40 | elif mime == "image": 41 | f = tgl.send_image 42 | elif mime == "audio": 43 | f = tgl.send_audio 44 | elif mime == "video": 45 | f = tgl.send_video 46 | print("Sending file with mime {} from path {}".format(mimetype, path)) 47 | f(receiver, path, utils.cb_rmp(path)) 48 | 49 | 50 | def run(msg, matches): 51 | url = matches[0] 52 | ext = matches[1] 53 | receiver = utils.get_receiver(msg) 54 | # Using thread... It's not really good 55 | # utils.async_download_to_file(url, ext, async_callback_download, receiver) 56 | # Using multiprocessing 57 | # First create a generic callback 58 | gcb = utils.generic_async_callback(async_callback_download, ext, receiver) 59 | # Then use the mp download 60 | utils.mp_download_to_file(url, ext, gcb, receiver) 61 | 62 | # Synchronous 63 | # synchronous(url, ext, receiver) 64 | 65 | 66 | __info__ = { 67 | "description": "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.", 68 | "usage": ["This plugin is automatic when you send an URL."], 69 | "patterns": [ 70 | "(https?://[\w\-\_\.\?\:\/\+\=\&]+\.(gifv|gif|mp4|pdf|ogg|zip|mp3|rar|wmv|doc|avi|webp))", 71 | ], 72 | "run": run, 73 | } 74 | -------------------------------------------------------------------------------- /plugins/money.py: -------------------------------------------------------------------------------- 1 | from gl import utils 2 | import re 3 | 4 | 5 | def cb(r, receiver, amount, fromCur, toCur): 6 | returnText = 'An error occurred.' 7 | html = r.text or '' 8 | moneyMatches = re.search("([\d.]+)", html) 9 | if moneyMatches: 10 | returnText = "{} {} is {} {}".format( 11 | amount, fromCur, moneyMatches.group(1), toCur) 12 | receiver.send_msg(returnText) 13 | 14 | 15 | def run(msg, matches): 16 | currencies = ["AED", "AFN", "ALL", "AMD", "ANG", "AOA", "ARS", "AUD", "AWG", "AZN", "BAM", "BBD", "BDT", "BGN", "BHD", "BIF", "BMD", "BND", "BOB", "BRL", "BSD", "BTC", "BTN", "BWP", "BYR", "BZD", "CAD", "CDF", "CHF", "CLF", "CLP", "CNH", "CNY", "COP", "CRC", "CUP", "CVE", "CZK", "DEM", "DJF", "DKK", "DOP", "DZD", "EGP", "ERN", "ETB", "EUR", "FIM", "FJD", "FKP", "FRF", "GBP", "GEL", "GHS", "GIP", "GMD", "GNF", "GTQ", "GYD", "HKD", "HNL", "HRK", "HTG", "HUF", "IDR", "IEP", "ILS", "INR", "IQD", "IRR", "ISK", "ITL", "JMD", "JOD", "JPY", "KES", "KGS", "KHR", "KMF", "KPW", "KRW", "KWD", "KYD", "KZT", "LAK", "LBP", "LKR", "LRD", "LSL", "LTL", "LVL", "LYD", "MAD", "MDL", "MGA", "MKD", "MMK", "MNT", "MOP", "MRO", "MUR", "MVR", "MWK", "MXN", "MYR", "MZN", "NAD", "NGN", "NIO", "NOK", "NPR", "NZD", "OMR", "PAB", "PEN", "PGK", "PHP", "PKG", "PKR", "PLN", "PYG", "QAR", "RON", "RSD", "RUB", "RWF", "SAR", "SBD", "SCR", "SDG", "SEK", "SGD", "SHP", "SLL", "SOS", "SRD", "STD", "SVC", "SYP", "SZL", "THB", "TJS", "TMT", "TND", "TOP", "TRY", "TTD", "TWD", "TZS", "UAH", "UGX", "USD", "UYU", "UZS", "VEF", "VND", "VUV", "WST", "XAF", "XCD", "XDR", "XOF", "XPF", "YER", "ZAR", "ZMK", "ZMW", "ZWL"] 17 | 18 | fromCur = matches[0].upper() 19 | amount = matches[1] 20 | toCur = matches[2].upper() 21 | 22 | if fromCur.isdigit(): 23 | fromCur, amount = amount.upper(), fromCur 24 | 25 | if fromCur not in currencies: 26 | return "ERROR: currency \"" + fromCur + "\" is not recognized" 27 | 28 | if toCur not in currencies: 29 | return "ERROR: currency \"" + toCur + "\" is not recognized" 30 | 31 | url = "https://www.google.com/finance/converter?a=" + \ 32 | amount + "&from=" + fromCur + "&to=" + toCur 33 | 34 | receiver = utils.get_receiver(msg) 35 | 36 | gcb = utils.gac(cb, receiver, amount, fromCur, toCur) 37 | utils.mp_requests('GET', url, gcb) 38 | 39 | __info__ = { 40 | "description": "Currency converter", 41 | "usage": ["!money (from currency) (amount) (to currency)"], 42 | "patterns": [ 43 | "^!m(?:oney)? ([\d\.]+) (\w+)(?: in)? (\w+)$", 44 | "^!m(?:oney)? (\w+) ([\d\.]+)(?: in)? (\w+)$"], 45 | "run": run 46 | } 47 | -------------------------------------------------------------------------------- /plugins/imgtosticker.py: -------------------------------------------------------------------------------- 1 | from gl import utils 2 | from PIL import Image 3 | import os 4 | 5 | 6 | class __ImgToSticker: 7 | def __init__(self): 8 | self.users = set() 9 | 10 | def remove_path(self, success, other, npath): 11 | try: 12 | os.remove(npath) 13 | except: 14 | pass 15 | 16 | def callback(self, success, path, receiver, userid): 17 | if userid in self.users: 18 | self.users.remove(userid) 19 | if success: 20 | # check if it's an image 21 | name = path.split("/")[-1].split(".")[0] 22 | extens = path.split("/")[-1].split(".")[-1] 23 | if extens.lower() not in ["png", "jpg", "jpeg", "gif"]: 24 | self.remove_path(True, True, path) 25 | receiver.send_msg("Sorry, that wasn't an accepted document. I accept png, jpg and gif.") 26 | return 27 | npath = "./{}.webp".format(name) 28 | try: 29 | im = Image.open(path).convert("RGBA") 30 | im.save(npath, "WEBP") 31 | receiver.send_document(npath, utils.gac(self.remove_path, npath)) 32 | except: 33 | os.remove(npath) 34 | finally: 35 | os.remove(path) 36 | 37 | def run(self, msg, matches): 38 | receiver = utils.get_receiver(msg) 39 | pattern = matches[0] 40 | userid = msg.src.id 41 | if pattern == "photo" or pattern == "document": 42 | if userid in self.users: 43 | # Check if he is in the list 44 | cb = utils.gac(self.callback, receiver, userid) 45 | getattr(msg, "load_{}".format(pattern))(cb) 46 | if pattern == "start": 47 | self.users.add(userid) 48 | return "You can send me an image now :)" 49 | if pattern == "stop": 50 | if userid in self.users: 51 | self.users.remove(userid) 52 | 53 | def preproc(self, msg): 54 | # Here maybe deactivate the user if he sends a message and he is activated 55 | # but this can be a really huge cpu time 56 | return msg 57 | 58 | 59 | __MyClass = __ImgToSticker() 60 | 61 | __info__ = { 62 | "description": "Convert a photo to sticker!", 63 | "usage": ["!imgtosticker start: Next photo you send, as image or document, it will try to convert to sticker and send you.", 64 | "!imgtosticker stop: Stop the service, won't convert the next image.", 65 | "If you are in \"start\" mode, send a photo as document or image, and get the sticker!"], 66 | "patterns": ["^!imgtosticker (start)$", 67 | "^!imgtosticker (stop)$", 68 | "^\[(photo)\]", 69 | "^\[(document)\]"], 70 | "run": __MyClass.run, 71 | # "pre_process": __MyClass.preproc 72 | } 73 | -------------------------------------------------------------------------------- /scripts/generate-plugins-table.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import sys 3 | import os 4 | import shutil 5 | import re 6 | sys.path.append(os.path.realpath(os.path.abspath('.'))) 7 | if os.path.isdir('tgl.pyc'): 8 | shutil.os.remove('tgl.pyc') 9 | shutil.copy('mock/tgl.py', '.') 10 | 11 | 12 | def safe_exit(code=0): 13 | if os.path.isfile('tgl.pyc'): 14 | shutil.os.remove('tgl.pyc') 15 | if os.path.isfile('tgl.py'): 16 | shutil.os.remove('./tgl.py') 17 | exit(code) 18 | 19 | 20 | def get_values(p): 21 | if not hasattr(p, '__info__'): 22 | return ('', '') 23 | info = p.__info__ 24 | desc = info.get('description') 25 | desc = desc or 'No description' 26 | usage = info.get('usage') 27 | usage = usage or '' 28 | if type(desc) is list: 29 | desc = '
'.join(desc) 30 | if type(usage) is list: 31 | usage = '
'.join(usage) 32 | return desc, usage 33 | 34 | 35 | activate_this_file = "./env/bin/activate_this.py" 36 | if not os.path.isfile(activate_this_file): 37 | print("You need to install the virtualenv") 38 | safe_exit(1) 39 | 40 | if not hasattr(sys, 'real_prefix'): 41 | print("You are not inside the virtualenv.") 42 | print("Do 'source env/bin/activate' before executing this") 43 | safe_exit(1) 44 | 45 | import tgl 46 | from gl import utils 47 | from gl import settings 48 | 49 | 50 | plugins = utils.clean_plugins(utils.get_all_plugins()) 51 | 52 | text = "| Name | Description | Usage |\n| ---- | ----------- | ----- |\n" 53 | base = "| {} | {} | {} |\n" 54 | utils.import_plugins(plugins, plugins) 55 | for p in sorted(plugins): 56 | realname = "{}.py".format(p) 57 | if not settings.PLUGINS.get(p): 58 | continue 59 | plug = settings.PLUGINS.get(p) 60 | desc, usage = get_values(plug) 61 | text += base.format(realname, desc, usage) 62 | 63 | 64 | with open("README.md", "r") as f: 65 | readmetext = f.read() 66 | 67 | reg1 = "Plugins\n---------\n+" 68 | reg2 = "\n\nInstallation\n---------" 69 | reg3 = "\|.*\|" 70 | 71 | m1 = re.search(reg1, readmetext) 72 | m2 = re.search(reg2, readmetext) 73 | 74 | if not (m1 and m2): 75 | print("There have some problem reading README.md, here have your plugins information to copy and paste manually:") 76 | print(text) 77 | safe_exit(1) 78 | 79 | oldtext = readmetext[m1.end():m2.start()] 80 | 81 | textcmp1 = re.search(reg3, oldtext, re.DOTALL) 82 | textcmp2 = re.search(reg3, text, re.DOTALL) 83 | 84 | if (textcmp1 and textcmp2) and textcmp1.group(0) == textcmp2.group(0): 85 | print("You already have the last plugins in README.md! ^^") 86 | safe_exit() 87 | 88 | print("I'm going to replace this text:\n------\n{}\n------\nFor this\n-----\n{}\n-----\n".format(oldtext, text)) 89 | resinput = input("If you want to make this changes, answer (Y): ") 90 | if resinput == "Y": 91 | prevp = readmetext[:m1.end()] 92 | nextp = readmetext[m2.start():] 93 | nextreadme = "{}{}{}".format(prevp, text, nextp) 94 | with open("README.md", "w") as f: 95 | f.write(nextreadme) 96 | print("The text had been replaced!") 97 | else: 98 | print("The text won't be replaced!") 99 | 100 | safe_exit() 101 | -------------------------------------------------------------------------------- /launch.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | THIS_DIR=$(cd $(dirname $0); pwd) 3 | RAM=`grep MemTotal /proc/meminfo | awk '{print $2}'` 4 | VBIN=virtualenv-3.4 5 | PYBIN=python 6 | 7 | 8 | if ! hash $VBIN 2>/dev/null; then 9 | VBIN=virtualenv3 10 | fi 11 | if ! hash $VBIN 2>/dev/null; then 12 | VBIN=virtualenv 13 | fi 14 | if ! hash $VBIN 2>/dev/null; then 15 | echo "You have to install virtualenv" 16 | exit 1 17 | fi 18 | 19 | cd $THIS_DIR 20 | 21 | update() { 22 | git pull 23 | git submodule update --init --recursive 24 | if [ ! -f ./env/bin/activate ]; then 25 | echo "You need virtualenv in env directory" 26 | echo "Run virtualenv -p python3 env" 27 | exit 1 28 | fi 29 | source env/bin/activate 30 | pip install -r requirements.txt 31 | } 32 | 33 | opt_install() { 34 | if [ ! -f ./env/bin/activate ]; then 35 | echo "You need virtualenv in env directory" 36 | echo "Run ./launch.sh install first" 37 | exit 1 38 | fi 39 | source env/bin/activate 40 | pip install -r opt_requirements.txt 41 | } 42 | 43 | 44 | install_no_lua() { 45 | if [ $RAM -lt 307200 ]; then 46 | ./configure --disable-extf --disable-liblua && make 47 | else 48 | ./configure --disable-liblua && make 49 | fi 50 | RET=$? 51 | if [ $RET -ne 0 ];then 52 | echo "Error installing tg"; exit $RET; 53 | fi 54 | } 55 | 56 | 57 | check_python3dev() { 58 | local res=1 59 | for python in python3.4 python3 python; do 60 | local path=`$python -c "from distutils.sysconfig import *; print(get_config_var('CONFINCLUDEPY'))"` 61 | if [[ $path == *"python3.4m"* ]]; then 62 | PYBIN=$python 63 | res=0 64 | fi 65 | done 66 | if [ $res -ne 0 ]; then 67 | echo "You need to install the python 3 libs, in ubuntu: 'sudo apt-get install python3-dev'" 68 | exit 1 69 | fi 70 | } 71 | 72 | 73 | install() { 74 | check_python3dev 75 | $VBIN -p python3 env 76 | RET=$? 77 | if [ $RET -ne 0 ]; then 78 | echo "Error creating the virtualenv with python 3, check the install instructions"; exit $RET 79 | fi 80 | update 81 | check_python3dev 82 | if [ $RAM -lt 307200 ]; then 83 | cd tg && ./configure --disable-extf && make 84 | else 85 | cd tg && ./configure && make 86 | fi 87 | if [ $? -ne 0 ]; then 88 | install_no_lua 89 | fi 90 | cd .. 91 | } 92 | 93 | if [ "$1" = "install" ]; then 94 | install 95 | elif [ "$1" = "update" ]; then 96 | update 97 | elif [ "$1" = "optdeps" ]; then 98 | opt_install 99 | else 100 | if [ ! -f ./tg/telegram.h ]; then 101 | echo "tg not found" 102 | echo "Run $0 install" 103 | exit 1 104 | fi 105 | if [ ! -f ./tg/bin/telegram-cli ]; then 106 | echo "tg binary not found" 107 | echo "Run $0 install" 108 | exit 1 109 | fi 110 | if [ ! -f ./env/bin/activate ]; then 111 | echo "You need virtualenv in env directory" 112 | echo "Run virtualenv -p python3 env" 113 | exit 1 114 | fi 115 | source env/bin/activate 116 | ./tg/bin/telegram-cli -k ./tg/tg-server.pub -Z bot/bot.py -l 1 -E 117 | fi 118 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | pybotgram 2 | ========= 3 | 4 | 5 | [![](https://travis-ci.org/rockneurotiko/pybotgram.svg?branch=master)](https://travis-ci.org/rockneurotiko/pybotgram) 6 | 7 | A Telegram Bot written in Python with plugins based in [yagop telegram-bot](https://github.com/yagop/telegram-bot) using [tg](https://github.com/vysheng/tg) 8 | 9 | 10 | State 11 | ---------- 12 | 13 | Currently the bot is in development, feel free to contribute, it would be really appreciated! 14 | 15 | 16 | Plugins 17 | --------- 18 | 19 | 20 | | Name | Description | Usage | 21 | | ---- | ----------- | ----- | 22 | | calc.py | A calculator to evaluate expressions | !calc (expression) | 23 | | channels.py | Plugin to manage channels.
Enable or disable channel. | !channel enable: enable current channel
!channel disable: disable current channel | 24 | | clever.py | Cleverbot plugin. | !clever (text): Say the text to cleverbot and receive the answer | 25 | | download_media.py | When bot receives a media msg, download the media to the file system. | This plugin is automatic when someone send a file. | 26 | | echo.py | Simplest plugin ever! | !echo (text) | 27 | | help.py | Help plugin.
Get info from other plugins. | !help: Show list of plugins.
!help all: Show all commands for every plugin.
!help [plugin name]: Commands for that plugin. | 28 | | imgtosticker.py | Convert a photo to sticker! | !imgtosticker start: Next photo you send, as image or document, it will try to convert to sticker and send you.
!imgtosticker stop: Stop the service, won't convert the next image.
If you are in "start" mode, send a photo as document or image, and get the sticker! | 29 | | media.py | When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin. | This plugin is automatic when you send an URL. | 30 | | money.py | Currency converter | !money (from currency) (amount) (to currency) | 31 | | plugins.py | Plugin to manage other plugins
Enable, disable or reload. | !plugins: list all plugins.
!plugins enable [plugin]: enable plugin.
!plugins disable [plugin]: disable plugin.
!plugins disable [plugin] chat: disable plugin only this chat.
!plugins reload: reloads all plugins. | 32 | 33 | 34 | Installation 35 | --------- 36 | 37 | In order to install it, you need some system dependencies. 38 | 39 | - tg dependencies: 40 | ``` 41 | # Tested on Ubuntu 14.04, for other OSs check out https://github.com/vysheng/tg#installation 42 | sudo apt-get install libreadline-dev libconfig-dev libssl-dev lua5.2 liblua5.2-dev libevent-dev libjansson-dev libpython-dev make 43 | ``` 44 | 45 | - bot dependencies: 46 | ``` 47 | sudo apt-get install git python3 libpython3-dev python-pip python3-pip 48 | sudo pip3 install virtualenv 49 | ``` 50 | 51 | - Optional dependencies: 52 | If you want to have all the plugins, you will have to install some more dependencies: 53 | ``` 54 | sudo apt-get install libtiff4-dev libjpeg8-dev zlib1g-dev libfreetype6-dev liblcms1-dev libwebp-dev 55 | ./launch.sh optdeps 56 | ``` 57 | 58 | To install in other OS, see this are the libraries that need extra dependencies: 59 | - [https://pypi.python.org/pypi/Pillow/2.1.0](https://pypi.python.org/pypi/Pillow/2.1.0) 60 | 61 | Plugins that you'll can't use if you don't install this optional dependencies: 62 | - `imgtosticker`: Use PIL (pillow) 63 | 64 | 65 | 66 | Once you have all dependencies, and the optional if you want, install the bot and run it: 67 | 68 | - bot: 69 | ``` 70 | cd $HOME 71 | git clone https://github.com/rockneurotiko/pybotgram/ 72 | cd pybotgram 73 | ./launch.sh install 74 | ./launch.sh # Will ask you for a phone number & confirmation code 75 | # (The number is like +cc00000000 where cc is the country code) 76 | ``` 77 | 78 | 79 | Enable more [`plugins`](https://github.com/rockneurotiko/pybotgram/tree/master/plugins) 80 | ------------- 81 | See the plugins list with `!plugins` command. 82 | 83 | Enable a disabled plugin by `!plugins enable [name]`. 84 | 85 | Disable an enabled plugin by `!plugins disable [name]`. 86 | 87 | Those commands require a privileged user, privileged users are defined inside `data/config.json` (generated by the bot), stop de bot and edit if necessary. 88 | 89 | The privileged users are identified with his telegram ID, and you can write all you want in `data/config.json`, in the list `sudo_users`, like this: 90 | ``` 91 | "sudo_users": [00000000, 11111111, 22222222, 33333333] 92 | ``` 93 | 94 | Contact me 95 | ------------ 96 | You can contact me [via Telegram](https://telegram.me/rock_neurotiko) but if you have an issue please [open](https://github.com/rockneurotiko/pybotgram/issues) one. 97 | -------------------------------------------------------------------------------- /plugins/plugins.py: -------------------------------------------------------------------------------- 1 | from gl import settings 2 | from gl import utils 3 | 4 | 5 | def generic_cfg(data, action, defaultt=list, field='enabled_plugins', fname="data/config.json", key=None): 6 | cfg = utils.load_cfg(fname) # load cfg 7 | plugs = cfg.get(field) or defaultt() 8 | if key is not None: 9 | if not plugs.get(key): 10 | plugs[key] = type(data)() 11 | if not hasattr(plugs[key], action): 12 | return 13 | getattr(plugs[key], action)(data) 14 | else: 15 | if not hasattr(plugs, action): 16 | return 17 | getattr(plugs, action)(data) 18 | cfg[field] = plugs 19 | utils.dump_cfg(fname, cfg) 20 | 21 | 22 | def getOrElse(field, defaultt=list, fname='data/config.json'): 23 | cfg = utils.load_cfg(fname) # load cfg 24 | return (cfg, cfg.get(field) or defaultt()) 25 | 26 | 27 | def list_plugins(only_enabled=False, receiver='', in_chat=False): 28 | text = "" 29 | allp = settings.ALL_PLUGINS if hasattr(settings, 'ALL_PLUGINS') else utils.clean_plugins(utils.get_all_plugins()) 30 | for plug in allp: 31 | status = utils.emojis.get('nope') 32 | if plug in settings.ENABLED_PLUGINS: 33 | status = utils.emojis.get('ok') 34 | if utils.is_plugin_disabled_on_chat(plug, receiver): 35 | status = '{} (in chat)'.format(utils.emojis.get('nope')) 36 | if not only_enabled or status == utils.emojis.get('ok'): 37 | text += "{} {}\n".format(plug, status) 38 | elif in_chat: 39 | text += "{} {}\n".format(plug, status) 40 | return text 41 | 42 | 43 | def enable_plugin(name, receiver): 44 | print("") 45 | if utils.plugin_enabled(name): 46 | return 'Plugin {} is enabled'.format(name) 47 | if utils.plugin_exists(name): 48 | generic_cfg(name, 'append') 49 | print("Added plugin {} to config file".format(name)) 50 | utils.reload_cfg_plugins() 51 | return list_plugins(True, receiver) 52 | else: 53 | return 'Plugin "{}" does not exists'.format(name) 54 | 55 | 56 | def disable_plugin(name, receiver): 57 | if not utils.plugin_exists(name): 58 | return 'Plugin {} does not exists'.format(name) 59 | if not utils.plugin_enabled(name): 60 | return 'Plugin {} is not enabled'.format(name) 61 | generic_cfg(name, 'remove') 62 | print("Removed plugin {} to config file".format(name)) 63 | utils.reload_cfg_plugins() 64 | return list_plugins(True, receiver) 65 | 66 | 67 | def enable_plugin_chat(name, receiver): 68 | if not utils.plugin_exists(name): 69 | return 'Plugin {} does not exists'.format(name) 70 | if not utils.is_plugin_disabled_on_chat(name, receiver): 71 | return 'Plugin {} is not disabled in this chat'.format(name) 72 | cfg, data = getOrElse('disabled_plugins_on_chat', dict) 73 | plgs = data.get(receiver) 74 | plgs.remove(name) 75 | data[receiver] = plgs 76 | generic_cfg(data, 'update', dict, field='disabled_plugins_on_chat') 77 | print("Enabled plugin {} in chat {} and saved".format(name, receiver)) 78 | cfg['disabled_plugins_on_chat'] = data 79 | utils.save_cfg_settings(cfg) 80 | return "Plugin {} enabled in the chat again! {}".format(name, utils.emojis['smile']) 81 | # return list_plugins(True, receiver, True) 82 | 83 | 84 | def disable_plugin_chat(name, receiver): 85 | if not utils.plugin_exists(name): 86 | return 'Plugin {} does not exists'.format(name) 87 | cfg, data = getOrElse('disabled_plugins_on_chat', dict) 88 | plgs = data.get(receiver) or set() 89 | plgs.add(name) 90 | data[receiver] = plgs 91 | generic_cfg(data, 'update', dict, field='disabled_plugins_on_chat') 92 | print("Disabled plugin {} in chat {} and saved".format(name, receiver)) 93 | cfg['disabled_plugins_on_chat'] = data 94 | utils.save_cfg_settings(cfg) 95 | return "Plugin {} disabled in the chat {}".format(name, utils.emojis['wut']) 96 | # return list_plugins(True, receiver, True) 97 | 98 | 99 | def run(msg, matches): 100 | receiver = utils.get_receiver_id(msg) 101 | if len(matches) == 1: 102 | if matches[0] == "!plugins": 103 | return list_plugins(receiver=receiver) 104 | elif matches[0] == "reload": 105 | utils.load_enabled_plugins() 106 | return list_plugins(True) 107 | elif len(matches) == 2: 108 | if matches[0] == 'enable': 109 | return enable_plugin(matches[1], receiver) 110 | else: 111 | print("Disable {} on this chat".format(matches[1])) 112 | return disable_plugin(matches[1], receiver) 113 | elif len(matches) == 3: 114 | if matches[0] == 'enable': 115 | return enable_plugin_chat(matches[1], receiver) 116 | else: 117 | return disable_plugin_chat(matches[1], receiver) 118 | 119 | 120 | __info__ = { 121 | "description": ["Plugin to manage other plugins", "Enable, disable or reload."], 122 | "usage": [ 123 | "!plugins: list all plugins.", 124 | "!plugins enable [plugin]: enable plugin.", 125 | "!plugins disable [plugin]: disable plugin.", 126 | "!plugins disable [plugin] chat: disable plugin only this chat.", 127 | "!plugins reload: reloads all plugins."], 128 | "patterns": [ 129 | "^!plugins$", 130 | "^!plugins? (enable|disable) ([\w_\.\-]+)$", 131 | "^!plugins? (enable|disable) ([\w_\.\-]+) (chat)?$", 132 | "^!plugins (reload)$", 133 | ], 134 | "run": run, 135 | 'privileged': True 136 | # "cron": lambda: print(), 137 | # "pre_process": lambda x: print(x) 138 | } 139 | -------------------------------------------------------------------------------- /scripts/create_base_plugin.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import re 3 | import os 4 | import sys 5 | BOTPATH = os.path.realpath(os.path.abspath('.')) 6 | sys.path.append(BOTPATH) 7 | 8 | 9 | capabilities = {'sett': 'from gl import settings', 10 | 'utils': 'from gl import utils', 11 | 'int': 'import requests', 12 | 're': 'import re', 13 | 'image': 'from PIL import Image', 14 | 'clever': 'import cleverbot'} 15 | 16 | 17 | def test_caps(caps): 18 | return caps == '' or all([x.lower().strip() in capabilities.keys() for x in caps.split(',')]) 19 | 20 | 21 | def check_plugin_valid(p): 22 | pnamer = "[\w_\.\-]+" 23 | match = re.match(pnamer, p) 24 | valid = match and match.group(0) == p 25 | valid = valid and p != "" 26 | return valid and p not in [f[:-3] for f in os.listdir('plugins') 27 | if os.path.isfile(os.path.join('plugins', f)) and 28 | not f.startswith('.') and 29 | not f.startswith('__') and 30 | f.endswith('.py')] 31 | 32 | 33 | def ask_for_n(message, end=''): 34 | res = [] 35 | goout = False 36 | print(message) 37 | while not goout: 38 | tmp = input() 39 | res.append(tmp) 40 | goout = tmp == end 41 | return res 42 | 43 | 44 | def ask_until(message, errormessage, check): 45 | goout = False 46 | while not goout: 47 | tmp = input("{}: ".format(message)) 48 | goout = True 49 | if not check(tmp): 50 | goout = False 51 | print(errormessage.format(tmp)) 52 | print('') # blank space ^^ 53 | return tmp 54 | 55 | full_file_base = """{imports} 56 | 57 | {content} 58 | 59 | {info} 60 | """ 61 | 62 | 63 | base_class = """ 64 | class _Plugin_{name}: 65 | 66 | def __init__(self): 67 | # Initialization 68 | pass 69 | 70 | {func} 71 | 72 | 73 | _Plugin_{name}_ins = _Plugin_{name}() 74 | """ 75 | 76 | 77 | class_base_func = """ def {name}(self, {params}): 78 | # Implement your {name} function here 79 | return {rtn}""" 80 | 81 | base_func = """ 82 | def {name}({params}): 83 | # Implement your {name} function here 84 | return {rtn}""" 85 | 86 | run_c_f = class_base_func.format(name="run", params="msg, matches", rtn="\"Some text to send\"") 87 | cron_c_f = class_base_func.format(name="cron", params="", rtn="") 88 | prep_c_f = class_base_func.format(name="pre_process", params="msg", rtn="msg") 89 | 90 | run_f = base_func.format(name="run", params="msg, matches", rtn="\"\"") 91 | cron_f = base_func.format(name="cron", params="", rtn="") 92 | prep_f = base_func.format(name="pre_process", params="msg", rtn="msg") 93 | 94 | 95 | base_info = """__info__ = {{ 96 | "description": {description}, 97 | "usage": {usage}, 98 | "patterns": {patterns}, 99 | {extra} 100 | }}""" 101 | 102 | extra_base = ' "{}": {}' 103 | 104 | priv_base = extra_base.format('privileged', '{}') 105 | run_base = extra_base.format('run', '{}') 106 | cron_base = extra_base.format('cron', '{}') 107 | prep_base = extra_base.format('pre_process', '{}') 108 | 109 | 110 | input("""Hi! 111 | Welcome to the base plugin creator. 112 | I'm gonna ask you some questions to build your plugin. 113 | Hit enter when you want to start rock! 114 | """) 115 | 116 | sp8 = ' ' * 8 117 | 118 | name = ask_until("What will be your plugin name?", "Sorry, plugin name \"{}\" is already taken or is not valid", check_plugin_valid) 119 | 120 | description = ask_for_n("Write the description for your the plugin \"{}\":".format(name))[:-1] 121 | 122 | longd = len(description) > 0 123 | description = '""' if not longd else '",\n{}"'.format(sp8).join(description) 124 | if longd: 125 | description = "[\n{}\"{}\"]".format(sp8, description) 126 | 127 | 128 | usages = ask_for_n('Put the usage list, one by one, and leave it blank when you want to finish:')[:-1] 129 | 130 | usages = "[\n{}\"{}\"]".format(sp8, '",\n{}"'.format(sp8).join(usages)) 131 | 132 | 133 | patterns = ask_for_n('Put the patterns list, one by one, and leave it blank when you want to finish:')[:-1] 134 | 135 | patterns = "[\n{}\"{}\"]".format(sp8, '",\n{}"'.format(sp8).join(patterns)) 136 | 137 | 138 | stateful = ask_until("Will the plugin \"{}\" be statefull or stateless? (full/less)".format(name), 'Write "full" or "less"', lambda x: x.lower() in ['full', 'less', 'f', 'l']).lower() 139 | stateful = stateful[0] == 'f' 140 | 141 | base_name_inf = "_Plugin_{}_ins.".format(name) if stateful else '' 142 | 143 | priv = ask_until("Will the plugin \"{}\" be only for privileged users? (y/n)".format(name), 'Write "y" or "n"', lambda x: x.lower() in ['y', 'n', 'yes', 'no']).lower() 144 | priv = priv[0] == 'y' 145 | priv_e = priv_base.format("True" if priv else "False") 146 | 147 | typ = ask_until('Of what type will be your plugin? (run/cron/preprocess)', 'Write "run", "cron" or "preprocess"', lambda x: x.lower() in ['run', 'cron', 'preprocess', 'r', 'c', 'p']).lower() 148 | 149 | content = '' 150 | if stateful: 151 | if typ[0] == 'r': 152 | func = run_c_f 153 | elif typ[0] == 'c': 154 | func = cron_c_f 155 | else: 156 | func = prep_c_f 157 | content = base_class.format(name=name, func=func) 158 | 159 | if typ[0] == 'r': 160 | content = run_f if content == '' else content 161 | typ_e = run_base.format('{}run'.format(base_name_inf)) 162 | if typ[0] == 'c': 163 | content = cron_f if content == '' else content 164 | typ_e = cron_base.format('{}cron'.format(base_name_inf)) 165 | if typ[0] == 'p': 166 | content = prep_f if content == '' else content 167 | typ_e = prep_base.format('{}pre_process'.format(base_name_inf)) 168 | 169 | 170 | extra_f = "{},\n{}".format(typ_e, priv_e) 171 | 172 | info_f = base_info.format(description=description, usage=usages, patterns=patterns, extra=extra_f) 173 | 174 | caps = ask_until("""What capabilities will have the plugin? (cap1, cap2, ...) 175 | 176 | The capabilities are: 177 | [Name]: [capability] 178 | ----------------- 179 | Settings: sett 180 | Utils: utils 181 | Internet: int 182 | Regular expressions: re 183 | Image: image 184 | Cleverbot: clever 185 | 186 | Write yours""", "Write a the capabilities separated by commas", test_caps) 187 | 188 | imports = '' if caps == '' else '\n'.join(sorted([capabilities[x] for x in {y.lower().strip() for y in caps.split(',')}])) 189 | 190 | 191 | final_path = './plugins/{}.py'.format(name) 192 | end_file = full_file_base.format(imports=imports, content=content, info=info_f) 193 | 194 | input("Hit enter to see how your file will look, then hit enter again to ask you if save it.\n") 195 | print("------------------ Start Plugin {} ------------------".format(name)) 196 | print(end_file) 197 | print("------------------ End Plugin {} ------------------".format(name)) 198 | input() 199 | 200 | save = ask_until("Do you want to save the plugin file in {}? (yes/no)".format(final_path), 'Type "yes" or "no"', lambda x: x.lower() in ['y', 'n', 'yes', 'no']).lower() 201 | if save[0] == 'y': 202 | with open(final_path, 'w') as f: 203 | f.write(end_file) 204 | print("File saved in {}".format(final_path)) 205 | else: 206 | print("Ok, I won't save it, see you!") 207 | -------------------------------------------------------------------------------- /bot/bot.py: -------------------------------------------------------------------------------- 1 | import tgl 2 | import pprint 3 | from functools import partial 4 | import sys 5 | import os 6 | import datetime 7 | BOTPATH = os.path.realpath(os.path.abspath('.')) 8 | sys.path.append(BOTPATH) 9 | from gl import settings 10 | from gl import utils 11 | 12 | 13 | our_id = 0 14 | now = datetime.datetime.now() 15 | pp = pprint.PrettyPrinter(indent=4) 16 | default_delay = 5 * 60 17 | 18 | started = False 19 | 20 | __version__ = '0.0.1' 21 | 22 | print("Python version: {}".format(sys.version)) 23 | 24 | 25 | def on_msg_receive(msg): 26 | global started 27 | if not started: 28 | return 29 | talkoneself = settings.TALK_ONESELF if hasattr(settings, 'TALK_ONESELF') else False 30 | receiver = utils.get_receiver(msg) 31 | # pp.pprint(msg) 32 | # pp.pprint(receiver) 33 | if msg_valid(msg): 34 | msg = _internal_preproc(msg) 35 | msg = pre_process_msg(msg) 36 | if msg: 37 | match_plugins(msg) 38 | if not talkoneself: # Only mark as read if we don't let us talk to ourself (means that we are the bot) 39 | receiver.mark_read(utils.ok_gen) 40 | 41 | 42 | def _internal_preproc(msg): 43 | if not msg.text and msg.media: 44 | msg = utils.props(msg) 45 | msg.text = "[{}]".format(msg.media.get('type')) 46 | return msg 47 | 48 | 49 | def pre_process_msg(msg): 50 | for name in settings.PLUGINS: 51 | if utils.plugin_have(name, 'pre_process'): 52 | msg = utils.execute_plugin_function(name, 'pre_process', msg) 53 | if not msg: 54 | return None # stop process :) 55 | return msg 56 | 57 | 58 | def match_plugins(msg): 59 | for name, plugin in settings.PLUGINS.items(): 60 | match_plugin(plugin, name, msg) 61 | 62 | 63 | def match_plugin(plugin, name, msg): 64 | if not hasattr(msg, 'text') or not msg.text or msg.text == '': 65 | return 66 | receiver = utils.get_receiver(msg) 67 | text = msg.text 68 | patterns = utils.get_infov(plugin, 'patterns', ()) 69 | for pattern in patterns: 70 | # print("Trying to match", pattern, "with", text) 71 | matches = utils.match_pattern(pattern, text) 72 | if not matches: 73 | continue 74 | print("Message matches: {}".format(pattern)) 75 | 76 | if utils.is_plugin_disabled_on_chat(name, receiver): 77 | return None 78 | 79 | if not utils.plugin_have_obj(plugin, 'run'): 80 | print("The plugin {} don't have run function".format(name)) 81 | continue 82 | if utils.warns_user_not_allowed(plugin, msg): 83 | continue 84 | result = utils.execute_plugin_function_obj(plugin, 'run', msg, matches) 85 | if result and type(result) == str: 86 | utils.send_large_msg(receiver, result) 87 | return # Only one pattern per plugin! 88 | 89 | 90 | def msg_valid(msg): 91 | talkoneself = settings.TALK_ONESELF if hasattr(settings, 'TALK_ONESELF') else False 92 | if not talkoneself and msg.out: 93 | print('\033[36mNot valid: msg from us\033[39m') 94 | return False 95 | 96 | if msg.date < now: 97 | print('\033[36mNot valid: old msg\033[39m') 98 | return False 99 | 100 | if not talkoneself and not msg.unread: 101 | print('\033[36mNot valid: readed\033[39m') 102 | return False 103 | 104 | if msg.service: 105 | print('\033[36mNot valid: service\033[39m') 106 | return False 107 | 108 | if not msg.dest.id: 109 | print('\033[36mNot valid: To id not provided\033[39m') 110 | return False 111 | 112 | if not msg.src.id: 113 | print('\033[36mNot valid: From id not provided\033[39m') 114 | return False 115 | 116 | if not talkoneself and msg.src.id == settings.OUR_ID: 117 | print('\033[36mNot valid: Msg from our id\033[39m') 118 | return False 119 | 120 | if msg.dest.type == 'encr_chat': 121 | print('\033[36mNot valid: Encrypted chat\033[39m') 122 | return False 123 | 124 | if msg.src.id == 777000: 125 | print('\033[36mNot valid: Telegram message\033[39m') 126 | return False 127 | 128 | return True 129 | 130 | 131 | def load_config(): 132 | if not os.path.isfile('data/config.json'): 133 | create_initial_cfg() 134 | return utils.load_cfg('data/config.json') 135 | 136 | 137 | def create_initial_cfg(): 138 | print("Creating new config file: data/config.json") 139 | global our_id 140 | oid = settings.OUR_ID if hasattr(settings, 'OUR_ID') else our_id 141 | cfg = { 142 | 'enabled_plugins': ['plugins', 143 | 'help', 144 | 'media'], 145 | 'sudo_users': [oid], 146 | 'disabled_channels': [], 147 | 'talk_oneself': False, 148 | } 149 | if not os.path.isdir('data'): 150 | os.mkdir('data') 151 | utils.dump_cfg('data/config.json', cfg) 152 | print("Data created :)") 153 | 154 | 155 | def on_binlog_replay_end(): 156 | global started 157 | started = True 158 | config = load_config() 159 | utils.save_cfg_settings(config) 160 | handle_sudoers(config) 161 | utils.load_enabled_plugins() 162 | cron_plugins() 163 | 164 | 165 | def handle_sudoers(cfg): 166 | suds = cfg.get('sudo_users') or (0,) 167 | for s in suds: 168 | print("Allowed sudo user: {}".format(s)) 169 | 170 | 171 | def on_get_difference_end(): 172 | pass 173 | 174 | 175 | def on_our_id(id): 176 | global our_id 177 | our_id = id 178 | settings.OUR_ID = id 179 | return "Set ID: " + str(our_id) 180 | 181 | 182 | def msg_cb(success, msg): 183 | pass 184 | # pp.pprint(success) 185 | # pp.pprint(msg) 186 | 187 | HISTORY_QUERY_SIZE = 100 188 | 189 | 190 | def history_cb(msg_list, peer, success, msgs): 191 | print(len(msgs)) 192 | msg_list.extend(msgs) 193 | print(len(msg_list)) 194 | if len(msgs) == HISTORY_QUERY_SIZE: 195 | tgl.get_history( 196 | peer, len(msg_list), HISTORY_QUERY_SIZE, partial(history_cb, msg_list, peer)) 197 | else: 198 | text = '\n'.join([str(i + 1) + ") " + x.text for (i, x) in enumerate(msgs[::-1]) if x.text is not None and not x.out]) 199 | peer.send_msg(text, msg_cb) 200 | 201 | 202 | def cb(success): 203 | pass 204 | # print(success) 205 | 206 | 207 | def on_secret_chat_update(peer, types): 208 | return "on_secret_chat_update" 209 | 210 | 211 | def on_user_update(user, what): 212 | # pp.pprint(user) 213 | # pp.pprint(what) 214 | pass 215 | 216 | 217 | def on_chat_update(chat, what): 218 | # pp.pprint(chat) 219 | # pp.pprint(what) 220 | pass 221 | 222 | 223 | @utils.delayed(default_delay) 224 | def cron_plugins(): 225 | print('yay!') 226 | 227 | 228 | def noop(): 229 | pass 230 | 231 | 232 | # Set callbacks 233 | tgl.set_on_binlog_replay_end(on_binlog_replay_end) 234 | tgl.set_on_get_difference_end(on_get_difference_end) 235 | tgl.set_on_our_id(on_our_id) 236 | tgl.set_on_msg_receive(on_msg_receive) 237 | tgl.set_on_secret_chat_update(on_secret_chat_update) 238 | tgl.set_on_user_update(on_user_update) 239 | tgl.set_on_chat_update(on_chat_update) 240 | tgl.set_on_loop(noop) # Make work the delayed functions :) 241 | 242 | # utils.import_plugins(utils.get_all_plugins(['test'])) 243 | # utils.execute_plugin_function('test', 'run', '', []) 244 | # utils.execute_plugin_function('test', 'run', '', []) 245 | # utils.execute_plugin_function('test', 'run', '', []) 246 | # utils.execute_plugin_function('test', 'run', '', []) 247 | # utils.execute_plugin_function('test', 'run', '', []) 248 | -------------------------------------------------------------------------------- /gl/utils.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from threading import Timer, Thread 4 | from functools import wraps 5 | import re 6 | import importlib 7 | import collections 8 | import os 9 | import inspect 10 | import requests 11 | import tempfile 12 | # from urllib.parse import urlparse 13 | from progressbar import ProgressBar 14 | try: 15 | import tgl 16 | except Exception as e: 17 | print(e) 18 | print("You are not injected in telegram. Maybe some actions won't work :S") 19 | from gl import settings 20 | import pickle 21 | import six 22 | import json 23 | import math 24 | from multiprocessing import Pool 25 | 26 | USER = 1 27 | CHAT = 2 28 | 29 | 30 | emojis = { 31 | 'smile': '😄' if six.PY3 else ':)', 32 | 'wut': '😐' if six.PY3 else ':|', 33 | 'nope': '❌' if six.PY3 else 'X', 34 | 'ok': '✔' if six.PY3 else 'V' 35 | } 36 | 37 | 38 | def get_receiver(msg): 39 | if msg.dest.type == USER: 40 | return msg.src 41 | if msg.dest.type == CHAT: 42 | return msg.dest 43 | if msg.dest.type == "encr_chat": 44 | print("Private chat!") 45 | return None 46 | 47 | 48 | def get_receiver_id(msg): 49 | rcv = get_receiver(msg) 50 | base = 'user#id' if rcv.type == 'user' else 'chat#id' 51 | return "{}{}".format(base, rcv.id) 52 | 53 | 54 | def ok_cb(success, msg): 55 | pass 56 | 57 | 58 | def ok_gen(*args): 59 | pass 60 | 61 | 62 | def get_safe_setting(name, default=dict): 63 | name = name.upper() # Settings always in upper case! 64 | if not hasattr(settings, name): 65 | setattr(settings, name, default()) 66 | return getattr(settings, name) 67 | 68 | 69 | def get_all_plugins(pluginsloaded=(), ignore=True): 70 | return [f for f in os.listdir('plugins') 71 | if os.path.isfile(os.path.join('plugins', f)) and 72 | not f.startswith(".") and 73 | f.endswith(".py") and 74 | (ignore or f[:-3] in pluginsloaded)] 75 | 76 | 77 | def clean_plugins(plugins): 78 | return [x[:-3] for x in plugins if not x.startswith("__init__")] 79 | 80 | 81 | def reload_cfg_plugins(prop='enabled_plugins'): 82 | cfg = load_cfg('data/config.json') 83 | nplugs = cfg.get(prop) or () 84 | oplugs = getattr(settings, prop.upper()) if hasattr(settings, prop.upper()) else () 85 | # oplugs = settings.ENABLED_PLUGINS 86 | diff1 = all(map(lambda x: x in oplugs, nplugs)) 87 | diff2 = all(map(lambda x: x in nplugs, oplugs)) 88 | if not diff1 or not diff2: 89 | save_cfg_settings(cfg) 90 | load_enabled_plugins() 91 | 92 | 93 | def plugin_enabled(name): 94 | return name in settings.PLUGINS.keys() 95 | 96 | 97 | def plugin_exists(name): 98 | if hasattr(settings, 'ALL_PLUGINS'): 99 | return name in settings.ALL_PLUGINS 100 | return name in clean_plugins(get_all_plugins()) 101 | 102 | 103 | def generic_cfg(data, action, defaultt=list, field='enabled_plugins', fname="data/config.json", key=None): 104 | cfg = load_cfg(fname) # load cfg 105 | plugs = cfg.get(field) or defaultt() 106 | if key is not None: 107 | if not plugs.get(key): 108 | plugs[key] = type(data)() 109 | if not hasattr(plugs[key], action): 110 | return 111 | try: 112 | getattr(plugs[key], action)(data) 113 | except: 114 | pass 115 | else: 116 | if not hasattr(plugs, action): 117 | return 118 | try: 119 | getattr(plugs, action)(data) 120 | except: 121 | pass 122 | cfg[field] = plugs 123 | dump_cfg(fname, cfg) 124 | 125 | 126 | def save_cfg_settings(cfg): 127 | if type(cfg) is not dict: 128 | return 129 | defaults = ('enabled_plugins', "sudo_users", "disabled_channels", "all_plugins") 130 | settings.ALL_PLUGINS = clean_plugins(get_all_plugins()) 131 | settings.ENABLED_PLUGINS = cfg.get('enabled_plugins') or () 132 | settings.SUDO_USERS = cfg.get('sudo_users') or () 133 | settings.DISABLED_CHANNELS = cfg.get('disabled_channels') or set() 134 | for k, v in cfg.items(): 135 | if k.lower() in defaults: continue 136 | setattr(settings, k.upper(), v) 137 | 138 | 139 | def get_enabled_paths(pluginsloaded=()): 140 | if hasattr(settings, 'ALL_PLUGINS'): 141 | return filter(lambda x: x in pluginsloaded, settings.ALL_PLUGINS) 142 | return get_all_plugins(pluginsloaded, False) 143 | 144 | 145 | def load_enabled_plugins(): 146 | eplugins = settings.ENABLED_PLUGINS if hasattr(settings, 'ENABLED_PLUGINS') else set() 147 | epaths = get_enabled_paths(eplugins) 148 | import_plugins(epaths, eplugins) 149 | 150 | 151 | def import_plugins(paths, eplugins=set()): 152 | # Some magic to dynamic import and reload ^^ 153 | plugins = settings.PLUGINS or {} 154 | errored = {} 155 | for p in paths: 156 | try: 157 | p = p[:-3] if p.endswith('.py') else p 158 | print("Loading plugin: {}".format(p)) 159 | if plugins.get(p): 160 | m = importlib.reload(plugins[p]) 161 | else: 162 | m = importlib.import_module('plugins.{}'.format(p)) 163 | plugins[p] = m 164 | except Exception as e: 165 | errored[p] = None 166 | print('\033[31mError loading plugin {}\033[39m'.format(p)) 167 | print('\033[31m{}\033[39m'.format(e)) 168 | plugins = clean_disabled(plugins, eplugins) 169 | settings.PLUGINS = plugins 170 | allplug = errored.copy() 171 | allplug.update(plugins) 172 | for p in filter(lambda x: x not in allplug, eplugins): 173 | print("\033[93mWarning: Plugin \"{}\" not loaded, maybe it's not in plugins directory anymore?\033[39m".format(p)) 174 | # Old way, can't reload in that way :S 175 | # plgs = __import__('plugins', globals(), locals(), paths, 0) 176 | # plugins = {} 177 | # for x in paths: 178 | # try: 179 | # print("Loading plugin: {}".format(x[:-3])) 180 | # plugins.update({x[:-3]: getattr(plgs, x[:-3])}) 181 | # except Exception as e: 182 | # print('\033[31mError loading plugin {}\033[39m'.format(x[:-3])) 183 | # print('\033[31m{}\033[39m'.format(e)) 184 | # settings.PLUGINS = plugins 185 | # settings.PLUGINS = {x[:-3]: getattr(plgs, x[:-3]) for x in paths} 186 | 187 | 188 | def clean_disabled(plugins, eplugins): 189 | if len(eplugins) == 0: 190 | return plugins 191 | nplugs = plugins.copy() 192 | for p in filter(lambda x: x not in eplugins, plugins.keys()): 193 | nplugs.pop(p) 194 | return nplugs 195 | 196 | 197 | def dump_cfg(path, data): 198 | try: 199 | with open(path, 'w') as f: 200 | json.dump(data, f, sort_keys=True, indent=4) 201 | except: 202 | pass 203 | 204 | 205 | def load_cfg(path): 206 | try: 207 | with open(path, 'r') as f: 208 | return json.load(f) 209 | except: 210 | return {} 211 | 212 | 213 | def dump_pick_cfg(path, data): 214 | try: 215 | with open(path, 'wb') as f: 216 | pickle.dump(data, f) 217 | except: 218 | pass 219 | 220 | 221 | def load_pick_cfg(path): 222 | try: 223 | with open(path, 'rb') as f: 224 | return pickle.load(f) 225 | except: 226 | return {} 227 | 228 | 229 | def plugin_have_obj(plugin, function): 230 | if not hasattr(plugin, '__info__'): 231 | return False 232 | return function in plugin.__info__.keys() 233 | 234 | 235 | def plugin_have(plugin, function): 236 | plg = settings.PLUGINS.get(plugin) 237 | if not plg: 238 | return False 239 | return plugin_have_obj(plg, function) 240 | # if not hasattr(plg, '__info__'): 241 | # return False 242 | # f = plg.__info__.get(function) 243 | # if not f: 244 | # return False 245 | # return True 246 | 247 | 248 | def execute_plugin_function_obj(plugin, function, *args, **kargs): 249 | if not plugin_have_obj(plugin, function): 250 | return 251 | return plugin.__info__[function](*args, **kargs) 252 | 253 | 254 | def execute_plugin_function(plugin, function, *args, **kargs): 255 | if not plugin_have(plugin, function): 256 | print("The plugin {} is not loaded or don't have {}".format(plugin, function)) 257 | return 258 | f = settings.PLUGINS[plugin].__info__[function] 259 | return f(*args, **kargs) 260 | 261 | 262 | def get_infov(plugin, val, default=None): 263 | if not hasattr(plugin, '__info__'): 264 | return default 265 | return plugin.__info__.get(val) or default 266 | 267 | 268 | def match_pattern(pattern, text, lower_case=False): 269 | if lower_case: 270 | text = text.lower() 271 | match = re.search(pattern, text) 272 | if match: 273 | return match.groups() if match.groups() != () else (match.group(),) 274 | return None 275 | 276 | 277 | def is_plugin_disabled_on_chat(name, receiver): 278 | if not hasattr(settings, 'DISABLED_PLUGINS_ON_CHAT'): return False 279 | disabl = settings.DISABLED_PLUGINS_ON_CHAT.get(receiver) or set() 280 | return name in disabl 281 | 282 | 283 | def warns_user_not_allowed(plugin, msg): 284 | if not user_allowed(plugin, msg): 285 | get_receiver(msg).send_msg("This plugin requires privileged user") 286 | return True 287 | return False 288 | 289 | 290 | def user_allowed(plugin, msg): 291 | if get_infov(plugin, 'privileged') and not is_sudo(msg): 292 | return False 293 | return True 294 | 295 | 296 | def is_sudo(msg): 297 | return isinstance(settings.SUDO_USERS, collections.Iterable) and msg.src.id in settings.SUDO_USERS 298 | 299 | 300 | def is_chat_msg(msg): 301 | return msg.dest.type == CHAT 302 | 303 | 304 | def cb_rmp(path): 305 | def aux(success, ncb): 306 | print("Removing {}".format(path)) 307 | try: 308 | os.remove(path) 309 | except: 310 | pass 311 | if ncb is not None and hasattr(ncb, '__call__'): 312 | ncb() 313 | return aux 314 | 315 | 316 | def download_to_file(path, ext): 317 | # Is it worth to have the same name? 318 | # ppath = urlparse(path).path.split("/") 319 | # ppath = ppath[-1] if len(ppath) > 0 else None 320 | _, file_name = tempfile.mkstemp("." + ext) 321 | r = requests.get(path, stream=True) 322 | total_length = r.headers.get('content-length') 323 | dl = 0 324 | with open(file_name, 'wb') as f: 325 | if total_length is None: 326 | f.write(r.content) 327 | else: 328 | total_length = int(total_length) 329 | pbar = ProgressBar(maxval=total_length).start() 330 | for chunk in r.iter_content(chunk_size=1024): 331 | if chunk: # filter out keep-alive new chunks 332 | pbar.update(dl * len(chunk)) 333 | dl += 1 334 | f.write(chunk) 335 | f.flush() 336 | pbar.finish() 337 | return file_name 338 | 339 | 340 | def send_large_msg(receiver, text): 341 | _send_large_msg_callback_aux(receiver, text)(True, receiver) 342 | 343 | 344 | # If text is longer than 4096 chars, send multiple msg. 345 | # https://core.telegram.org/method/messages.sendMessage 346 | def _send_large_msg_callback_aux(receiver, text): 347 | def aux(success, dest): 348 | text_max = 4096 349 | tlen = len(text) 350 | nmsg = math.ceil(tlen / text_max) 351 | if nmsg <= 1: 352 | receiver.send_msg(text, ok_cb) 353 | else: 354 | ntext = text[:text_max] 355 | rest = text[text_max:] 356 | f = _send_large_msg_callback_aux(receiver, rest) 357 | tgl.send_msg(receiver, ntext, f, True) 358 | return aux 359 | 360 | 361 | class dotdict(dict): 362 | """dot.notation access to dictionary attributes""" 363 | def __getattr__(self, attr): 364 | return self.get(attr) 365 | __setattr = dict.__setitem__ 366 | __delattr = dict.__delitem__ 367 | 368 | 369 | def props(obj): 370 | """ 371 | Convert an object in a dotdict 372 | """ 373 | pr = dotdict() 374 | for name in dir(obj): 375 | try: 376 | value = getattr(obj, name) 377 | if not name.startswith('__') and not inspect.ismethod(value): 378 | pr[name] = value 379 | except: 380 | continue 381 | return pr 382 | 383 | 384 | def generic_async_callback(f, *args, **kargs): 385 | """ 386 | Create a generic callback. 387 | f: callback function 388 | *args and **kargs will be parameters to call 389 | ALWAYS the first parameter will be the parameters passed to the aux function 390 | """ 391 | def aux(*args2, **kargs2): 392 | newt = args2 + args 393 | newk = kargs.copy() 394 | newk.update(kargs2) 395 | f(*newt, **newk) 396 | return aux 397 | 398 | gac = generic_async_callback 399 | 400 | 401 | def poolit(f, cb, *args, **kargs): 402 | """ 403 | f: Function to call asynchronously 404 | cb: Callback to call with the result. This only take one parameter. Use generic_async_callback to generate a callback from a function 405 | args and kargs are sended to the function 406 | """ 407 | pool = Pool() 408 | pool.apply_async(f, args, kargs, cb) 409 | 410 | 411 | def mp_download_to_file(path, ext, cb, *args, **kargs): 412 | poolit(download_to_file, cb, path, ext) 413 | 414 | 415 | def mp_requests(mode, path, cb, params=None): 416 | kargs = {"params": params} if params is not None else {} 417 | if not hasattr(requests, mode.lower()): 418 | return 419 | f = getattr(requests, mode.lower()) 420 | poolit(f, cb, path, **kargs) 421 | 422 | 423 | def delayed(seconds): 424 | def decorator(f): 425 | @wraps(f) 426 | def wrapper(*args, **kargs): 427 | t = Timer(seconds, f, args, kargs) 428 | t.start() 429 | return wrapper 430 | return decorator 431 | 432 | 433 | # Remove this functions? MP is much better 434 | 435 | # # From http://code.activestate.com/recipes/576684-simple-threading-decorator/ 436 | # def run_async(func): 437 | # @wraps(func) 438 | # def async_func(*args, **kwargs): 439 | # func_hl = Thread(target=func, args=args, kwargs=kwargs) 440 | # func_hl.start() 441 | # return func_hl 442 | # return async_func 443 | 444 | 445 | # def auxdasync(path, ext): 446 | # _, file_name = tempfile.mkstemp("." + ext) 447 | # r = requests.get(path, stream=True) 448 | # total_length = r.headers.get('content-length') 449 | # dl = 0 450 | # with open(file_name, 'wb') as f: 451 | # if total_length is None: 452 | # f.write(r.content) 453 | # else: 454 | # total_length = int(total_length) 455 | # for chunk in r.iter_content(chunk_size=1024): 456 | # if chunk: # filter out keep-alive new chunks 457 | # print("{} / {}".format(dl * len(chunk), total_length)) 458 | # dl += 1 459 | # f.write(chunk) 460 | # f.flush() 461 | # return file_name 462 | 463 | 464 | # @run_async 465 | # def async_download_to_file(path, ext, cb, *args, **kargs): 466 | # rpath = None 467 | # try: 468 | # print("Trying") 469 | # rpath = auxdasync(path, ext) 470 | # print("Tring2") 471 | # except Exception as e: 472 | # print("Error: ", e) 473 | # print("Outside: ", rpath) 474 | # cb(rpath, ext, *args, **kargs) 475 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | 663 | --------------------------------------------------------------------------------