Skip to content

Commit

Permalink
Merge pull request #54 from leandrotoledo/testing
Browse files Browse the repository at this point in the history
Merge Testing branch
  • Loading branch information
leandrotoledo committed Sep 4, 2015
2 parents 881b0b3 + 62f06da commit e693922
Show file tree
Hide file tree
Showing 42 changed files with 1,526 additions and 664 deletions.
4 changes: 3 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ python:
- "2.7"
- "3.3"
- "3.4"
- "pypy"
- "pypy3"
install:
- pip install coveralls
script:
coverage run telegram_test.py
coverage run tests/test_*.py
after_success:
coveralls
1 change: 1 addition & 0 deletions AUTHORS.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ The following wonderful people contributed directly or indirectly to this projec
- `JASON0916 <https://github.com/JASON0916>`_
- `JRoot3D <https://github.com/JRoot3D>`_
- `macrojames <https://github.com/macrojames>`_
- `njittam <https://github.com/njittam>`_
- `Rahiel Kasim <https://github.com/rahiel>`_
- `sooyhwang <https://github.com/sooyhwang>`_
- `wjt <https://github.com/wjt>`_
Expand Down
File renamed without changes.
19 changes: 13 additions & 6 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
help:
@echo " clean remove unwanted stuff"
@echo " lint check style with flake8"
@echo " test run tests"
.PHONY: clean pep8 lint test

clean:
rm -fr build
Expand All @@ -10,8 +7,18 @@ clean:
find . -name '*.pyo' -exec rm -f {} \;
find . -name '*~' -exec rm -f {} \;

pep8:
flake8 telegram

lint:
flake8 --doctests --max-complexity 10 telegram
pylint -E telegram

test:
python telegram_test.py
@- $(foreach TEST, $(wildcard tests/test_*.py), python $(TEST))

help:
@echo "Available targets:"
@echo "- clean Clean up the source directory"
@echo "- pep8 Check style with flake8"
@echo "- lint Check style with pylint"
@echo "- test Run tests"
File renamed without changes.
89 changes: 89 additions & 0 deletions examples/command_handler_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# There could be some unused imports
from inspect import getmembers, ismethod
import threading
import logging
import telegram
import time
from telegram import CommandHandlerWithHelp, CommandHandler
class ExampleCommandHandler(CommandHandlerWithHelp):
"""This is an example how to use a CommandHandlerWithHelp or just a CommandHandler.
If You want to use a CommandHandler it is very easy.
create a class which inherits a CommandHandler.
create a method in this class which start with 'command_' and takes 1 argument: 'update' (which comes directly from
getUpdate()).
If you inherit CommandHandlerWithHelp it also creates a nice /help for you.
"""
def __init__(self, bot): # only necessary for a WithHelp
super(ExampleCommandHandler, self).__init__(bot)
self._help_title = 'Welcome this is a help file!' # optional
self._help_before_list = """
Yeah here I explain some things about this bot.
and of course I can do this in Multiple lines.
""" # default is empty
self._help_list_title = ' These are the available commands:' # optional
self._help_after_list = ' These are some footnotes' # default is empty
self.is_reply = True # default is True

# only necessary if you want to override to default
def _command_not_found(self, update):
"""Inform the telegram user that the command was not found."""
chat_id = update.message.chat.id
reply_to = update.message.message_id
message = "Sorry, I don't know how to do {command}.".format(command=update.message.text.split(' ')[0])
self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to)

# creates /test command. This code gets called when a telegram user enters /test
def command_test(self, update):
""" Test if the server is online. """
chat_id = update.message.chat.id
reply_to = update.message.message_id
message = 'Yeah, the server is online!'
self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to)

# creates /parrot command
def command_parrot(self, update):
""" Says back what you say after the command"""
chat_id = update.message.chat.id
reply_to = update.message.message_id
send = update.message.text.split(' ')
message = update.message.text[len(send[0]):]
if len(send) == 1:
message = '...'
self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to)

# creates /p command
def command_p(self, update):
"""Does the same as parrot."""
return self.command_parrot(update)

# this doesn't create a command.
def another_test(self, update):
""" This won't be called by the CommandHandler.
This is an example of a function that isn't a command in telegram.
Because it didn't start with 'command_'.
"""
chat_id = update.message.chat.id
reply_to = update.message.message_id
message = 'Yeah, this is another test'
self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to)


class Exampe2CommandHandler(CommandHandler):
"""
This is an example of a small working CommandHandler with only one command.
"""
def command_test(self, update):
""" Test if the server is online. """
chat_id = update.message.chat.id
reply_to = update.message.message_id
message = 'Yeah, the server is online!'
self.bot.sendMessage(chat_id, message, reply_to_message_id=reply_to)

if __name__ == '__main__':
import telegram
token = '' # use your own token here
Bot = telegram.Bot(token=token)
test_command_handler = ExampleCommandHandler(Bot)
test_command_handler.run()
7 changes: 4 additions & 3 deletions telegram/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,13 @@
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].

"""A library that provides a Python interface to the Telegram Bot API"""

__author__ = 'leandrotoledodesouza@gmail.com'
__version__ = '2.7.1'

from .base import TelegramObject
from .user import User
from .message import Message
from .update import Update
from .groupchat import GroupChat
from .photosize import PhotoSize
from .audio import Audio
Expand All @@ -39,10 +38,12 @@
from .replykeyboardmarkup import ReplyKeyboardMarkup
from .replykeyboardhide import ReplyKeyboardHide
from .forcereply import ForceReply
from .inputfile import InputFile
from .error import TelegramError
from .inputfile import InputFile
from .nullhandler import NullHandler
from .emoji import Emoji
from .message import Message
from .update import Update
from .bot import Bot

__all__ = ['Bot', 'Emoji', 'TelegramError', 'InputFile', 'ReplyMarkup',
Expand Down
70 changes: 42 additions & 28 deletions telegram/audio.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,43 +16,57 @@
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].

"""This module contains a object that represents a Telegram Audio"""

from telegram import TelegramObject


class Audio(TelegramObject):
"""This object represents a Telegram Audio.
Attributes:
file_id (str):
duration (int):
performer (str):
title (str):
mime_type (str):
file_size (int):
Args:
file_id (str):
duration (int):
**kwargs: Arbitrary keyword arguments.
Keyword Args:
performer (Optional[str]):
title (Optional[str]):
mime_type (Optional[str]):
file_size (Optional[int]):
"""

def __init__(self,
file_id,
duration,
performer=None,
title=None,
mime_type=None,
file_size=None):
**kwargs):
# Required
self.file_id = file_id
self.duration = duration
self.performer = performer
self.title = title
self.mime_type = mime_type
self.file_size = file_size
self.duration = int(duration)
# Optionals
self.performer = kwargs.get('performer', '')
self.title = kwargs.get('title', '')
self.mime_type = kwargs.get('mime_type', '')
self.file_size = int(kwargs.get('file_size', 0))

@staticmethod
def de_json(data):
return Audio(file_id=data.get('file_id', None),
duration=data.get('duration', None),
performer=data.get('performer', None),
title=data.get('title', None),
mime_type=data.get('mime_type', None),
file_size=data.get('file_size', None))

def to_dict(self):
data = {'file_id': self.file_id,
'duration': self.duration}
if self.performer:
data['performer'] = self.performer
if self.title:
data['title'] = self.title
if self.mime_type:
data['mime_type'] = self.mime_type
if self.file_size:
data['file_size'] = self.file_size
return data
"""
Args:
data (str):
Returns:
telegram.Audio:
"""
if not data:
return None

return Audio(**data)
32 changes: 28 additions & 4 deletions telegram/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,14 @@
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].

"""Base class for Telegram Objects"""

import json
from abc import ABCMeta, abstractmethod
from abc import ABCMeta


class TelegramObject(object):
"""Base class for most telegram object"""
"""Base class for most telegram objects"""

__metaclass__ = ABCMeta

Expand All @@ -34,11 +35,34 @@ def __getitem__(self, item):

@staticmethod
def de_json(data):
"""
Args:
data (str):
Returns:
telegram.TelegramObject:
"""
raise NotImplementedError

def to_json(self):
"""
Returns:
str:
"""
return json.dumps(self.to_dict())

@abstractmethod
def to_dict(self):
return
"""
Returns:
dict:
"""
data = dict()

for key, value in self.__dict__.items():
if value:
if hasattr(value, 'to_dict'):
data[key] = value.to_dict()
else:
data[key] = value

return data

0 comments on commit e693922

Please sign in to comment.