Exemplo n.º 1
0
URL_HOSTNAME = os.getenv('URL_HOSTNAME', None)
# URL_HOSTNAME environment variable, can be None

URL_PATH = os.getenv('URL_PATH', None)
assert (URL_PATH is not None)  # URL_PATH environment variable

logger = logging.getLogger(__name__)
logging.add_colored_handler(level=logging.DEBUG)

app = Flask(__name__)

bot = Teleflask(API_KEY,
                hostname=URL_HOSTNAME,
                hostpath=URL_PATH,
                hookpath="/income/{API_KEY}")
bot.init_app(app)


@app.errorhandler(404)
def url_404(error):
    return "404.", 404


# end def


@app.route("/", methods=["GET", "POST"])
def url_root():
    return '<b>Hello world</b> from your <a href="https://github.com/luckydonald/docker-telegram-bot/">flask based telegram bot</b>.<br>' \
           'This is a <i>normal browser page</i>.'
Exemplo n.º 2
0
class SomeTestCase(unittest.TestCase):
    def setUp(self):
        os.environ.setdefault("URL_HOSTNAME", "example.com")

        app = Flask(__name__)
        app.config.from_pyfile("testconfig.py")
        self.app = app
        self.app_test = app.test_client()  # get a test client
        self.bot = Teleflask(API_KEY, return_python_objects=True)

        # replace the :class:`pytgbot.Bot` instance with something testable. (not using TG server)
        # All methods now return the stuff they would sent to the telegram servers as json instead.
        # This is not usable with the :class:`teleflask.message.Message` (sub)types.
        self.bot.bot = BotTestable(API_KEY, return_python_objects=self.bot._return_python_objects)

        # Init must be before replacing the ``bot.bot``,
        # because else the :meth:`Bot.getWebhook` won't work as expected in startup.
        self.bot.init_app(app)

        # Array to hold information about the called callbacks:
        self.callbacks_status = {}

        # Get the update_path to be able to test via emulating incoming updates
        self.update_path, self.update_url = self.bot.calculate_webhook_url(hostname=self.bot.hostname, hostpath=self.bot.hostpath, hookpath=self.bot.hookpath)

    def tearDown(self):
        pass
        # os.close(self.db_fd)
        # os.unlink(flaskr.app.config['DATABASE'])
    # end def

    data_cmd = {
        "update_id": 10000,
        "message": {
            "message_id": 4458,
            "from": {
                "id": 1234,
                "first_name": "Test User",
                "username": "******"
            },
            "chat": {
                "id": 1234,
                "first_name": "Test User",
                "username": "******",
                "type": "private"
            },
            "date": 1487612335,
            "text": "/test 123",
            "entities": [
                {
                    "type": "bot_command",
                    "offset": 0,
                    "length": 5
                }
            ]
        }
    }

    def test_webhook(self):
        self.assertEqual(self.update_url.replace(API_KEY, "{API_KEY}"), "https://example.com/income/{API_KEY}")
    # end def

    def test_command(self):
        @self.bot.command("test")
        def _callback_test_command(update, text):
            self.callbacks_status["_callback_test_command"] = text
        # end def

        self.app_test.post(self.update_path, data=json.dumps(self.data_cmd), content_type='application/json')

        self.assertIn("_callback_test_command", self.callbacks_status, "@command('test') func executed")
        self.assertEquals(self.callbacks_status["_callback_test_command"], "123")
    # end def

    def test_on_message(self):
        @self.bot.on_message
        def _callback_test_on_message(msg):
            self.callbacks_status["_callback_test_on_message"] = msg
        # end def

        self.app_test.post(self.update_path, data=json.dumps(self.data_cmd), content_type='application/json')

        self.assertIn("_callback_test_on_message", self.callbacks_status, "@on_message func executed")
        msg = self.callbacks_status["_callback_test_on_message"]
        from pytgbot.api_types.receivable.updates import Message
        self.assertIsInstance(msg, Message)
        self.assertEquals(msg.to_array(), self.data_cmd["message"])
    # end def

    def test_on_message2(self):
        @self.bot.on_message("text")
        def _callback_test_on_message2(msg):
            self.callbacks_status["_callback_test_on_message2"] = msg
        # end def

        self.app_test.post(self.update_path, data=json.dumps(self.data_cmd), content_type='application/json')

        self.assertIn("_callback_test_on_message2", self.callbacks_status, "@on_message('text') func executed")
        msg = self.callbacks_status["_callback_test_on_message2"]
        from pytgbot.api_types.receivable.updates import Message
        self.assertIsInstance(msg, Message)
        self.assertEquals(msg.to_array(), self.data_cmd["message"])
    # end def

    def test_on_message3(self):
        @self.bot.on_message("photo")
        def _callback_test_on_message3(msg):
            self.callbacks_status["_callback_test_on_message3"] = msg
        # end def

        self.app_test.post(self.update_path, data=json.dumps(self.data_cmd), content_type='application/json')

        self.assertNotIn("_callback_test_on_message3", self.callbacks_status, "@on_message('photo') func not executed")
Exemplo n.º 3
0
# -*- coding: utf-8 -*-
from flask import Flask
from teleflask import Teleflask
from teleflask.messages import TextMessage, PlainMessage, MarkdownMessage, HTMLMessage


__author__ = 'luckydonald'

from somewhere import API_KEY  # I import it from some file which is kept private, not in git.
# Just set API_KEY = "your-api-key".
app = Flask(__name__)
bot = Teleflask(API_KEY)
bot.init_app(app)


@app.route("/")
def index():
    return "This is a normal Flask page."
# end def


# Register the /start command
@bot.command("start")
def start(update, text):
    # update is the update object. It is of type pytgbot.api_types.receivable.updates.Update
    # text is the text after the command. Can be empty. Type is str.
    return HTMLMessage("<b>Hello!</b> Thanks for using @" + app.username + "!")
    # return TextMessage("<b>Hello!</b> Thanks for using @" + app.username + "!", parse_mode="html")
# end def

Exemplo n.º 4
0
class SomeTestCase(unittest.TestCase):
    def setUp(self):
        os.environ.setdefault("URL_HOSTNAME", "example.com")

        app = Flask(__name__)
        app.config.from_pyfile("testconfig.py")
        self.app = app
        self.app_test = app.test_client()  # get a test client
        self.bot = Teleflask(API_KEY, return_python_objects=True)

        # replace the :class:`pytgbot.Bot` instance with something testable. (not using TG server)
        # All methods now return the stuff they would sent to the telegram servers as json instead.
        # This is not usable with the :class:`teleflask.message.Message` (sub)types.
        self.bot.bot = BotTestable(
            API_KEY, return_python_objects=self.bot._return_python_objects)

        # Init must be before replacing the ``bot.bot``,
        # because else the :meth:`Bot.getWebhook` won't work as expected in startup.
        self.bot.init_app(app)

        # Array to hold information about the called callbacks:
        self.callbacks_status = {}

        # Get the update_path to be able to test via emulating incoming updates
        self.update_path, self.update_url = self.bot.calculate_webhook_url(
            hostname=self.bot.hostname,
            hostpath=self.bot.hostpath,
            hookpath=self.bot.hookpath)

    def tearDown(self):
        pass
        # os.close(self.db_fd)
        # os.unlink(flaskr.app.config['DATABASE'])

    # end def

    data_cmd = {
        "update_id": 10000,
        "message": {
            "message_id": 4458,
            "from": {
                "id": 1234,
                "first_name": "Test User",
                "username": "******"
            },
            "chat": {
                "id": 1234,
                "first_name": "Test User",
                "username": "******",
                "type": "private"
            },
            "date": 1487612335,
            "text": "/test 123",
            "entities": [{
                "type": "bot_command",
                "offset": 0,
                "length": 5
            }]
        }
    }

    def test_webhook(self):
        self.assertEqual(self.update_url.replace(API_KEY, "{API_KEY}"),
                         "https://example.com/income/{API_KEY}")

    # end def

    def test_command(self):
        @self.bot.command("test")
        def _callback_test_command(update, text):
            self.callbacks_status["_callback_test_command"] = text

        # end def

        self.app_test.post(self.update_path,
                           data=json.dumps(self.data_cmd),
                           content_type='application/json')

        self.assertIn("_callback_test_command", self.callbacks_status,
                      "@command('test') func executed")
        self.assertEquals(self.callbacks_status["_callback_test_command"],
                          "123")

    # end def

    def test_on_message(self):
        @self.bot.on_message
        def _callback_test_on_message(msg):
            self.callbacks_status["_callback_test_on_message"] = msg

        # end def

        self.app_test.post(self.update_path,
                           data=json.dumps(self.data_cmd),
                           content_type='application/json')

        self.assertIn("_callback_test_on_message", self.callbacks_status,
                      "@on_message func executed")
        msg = self.callbacks_status["_callback_test_on_message"]
        from pytgbot.api_types.receivable.updates import Message
        self.assertIsInstance(msg, Message)
        self.assertEquals(msg.to_array(), self.data_cmd["message"])

    # end def

    def test_on_message2(self):
        @self.bot.on_message("text")
        def _callback_test_on_message2(msg):
            self.callbacks_status["_callback_test_on_message2"] = msg

        # end def

        self.app_test.post(self.update_path,
                           data=json.dumps(self.data_cmd),
                           content_type='application/json')

        self.assertIn("_callback_test_on_message2", self.callbacks_status,
                      "@on_message('text') func executed")
        msg = self.callbacks_status["_callback_test_on_message2"]
        from pytgbot.api_types.receivable.updates import Message
        self.assertIsInstance(msg, Message)
        self.assertEquals(msg.to_array(), self.data_cmd["message"])

    # end def

    def test_on_message3(self):
        @self.bot.on_message("photo")
        def _callback_test_on_message3(msg):
            self.callbacks_status["_callback_test_on_message3"] = msg

        # end def

        self.app_test.post(self.update_path,
                           data=json.dumps(self.data_cmd),
                           content_type='application/json')

        self.assertNotIn("_callback_test_on_message3", self.callbacks_status,
                         "@on_message('photo') func not executed")