Skip to content

Commit

Permalink
Add message send command (#2)
Browse files Browse the repository at this point in the history
* Add `message send` command

The new `send` command sends a text message to a
chat.

    tgm message send --chat-id 161035319 --text ‘hello’

Chat IDs can be users or groups.
  • Loading branch information
zmoog committed Feb 11, 2023
1 parent 7098729 commit 00dd87e
Show file tree
Hide file tree
Showing 6 changed files with 140 additions and 12 deletions.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ Install this tool using `pip`:

## Usage

For sending a simple text message to a user o group, run:

export TELEGRAM_TOKEN='bot123456:de4dbeefde4dbeefde4dbeefde4dbeefde4dbeef'

$ tgm message send --chat-id 123456 --text 'Hello'
message-id: 676

For help, run:

telegram-cli --help
Expand Down
9 changes: 6 additions & 3 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,14 @@ def get_long_description():
packages=["telegram_cli"],
entry_points="""
[console_scripts]
telegram-cli=telegram_cli.cli:cli
tgm=telegram_cli.cli:cli
""",
install_requires=["click"],
install_requires=[
"click",
"requests",
],
extras_require={
"test": ["pytest"]
"test": ["pytest", "pytest-recording"]
},
python_requires=">=3.7",
)
31 changes: 22 additions & 9 deletions telegram_cli/cli.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,34 @@
import click

from . import telegram


@click.group()
@click.version_option()
def cli():
"Python CLI tool and library for sending messages to Telegram"


@cli.command(name="command")
@click.argument(
"example"
@cli.group()
@click.pass_context
def message(ctx: click.Context):
ctx.ensure_object(dict)


@message.command(name="send")
@click.option(
"--text",
required=True,
)
@click.option(
"-o",
"--option",
help="An example option",
"--chat-id",
required=True,
)
def first_command(example, option):
"Command description goes here"
click.echo("Here is some output")
@click.pass_context
def send(ctx: click.Context, text: str, chat_id: str):

client = telegram.Client.from_envorinment()
resp = client.send(text, chat_id)

message_id = resp.get("result", {}).get("message_id", "No message id found")
click.echo(f"message-id: {message_id}")
40 changes: 40 additions & 0 deletions telegram_cli/telegram.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import os
from typing import Any, Dict

import requests


class Client:
"""Telegram client."""

def __init__(self, token: str):
self.token = token

@staticmethod
def from_envorinment() -> "Client":
"""Create a client from the TELEGRAM_TOKEN environment variable."""

if "TELEGRAM_TOKEN" not in os.environ:
raise Exception(
"TELEGRAM_TOKEN environment variable not found. "
"Please set it to your Telegram API token."
)

return Client(token=os.environ['TELEGRAM_TOKEN'])

def send(self, msg: str, chat_id: str) -> Dict[str, Any]:
"""Send a message to a chat."""

params = {
'chat_id': chat_id,
'text': msg
}

r = requests.get(
f'https://api.telegram.org/{self.token}/sendMessage',
params=params
)

r.raise_for_status()

return r.json()
42 changes: 42 additions & 0 deletions tests/cassettes/test_message/test_send.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
interactions:
- request:
body: null
headers:
Accept:
- '*/*'
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- python-requests/2.28.2
method: GET
uri: https://api.telegram.org/1234567890abcdef1234567890abcdef/sendMessage?chat_id=161035319&text=%27Hello%2C+world%21%27
response:
body:
string: '{"ok":true,"result":{"message_id":665,"from":{"id":123,"is_bot":true,"first_name":"Hogwarts
Bot","username":"hogwarts_api_bot"},"chat":{"id":456,"first_name":"Maurizio","last_name":"Branca","username":"zmoog","type":"private"},"date":1675921959,"text":"''Hello,
world!''"}}'
headers:
Access-Control-Allow-Methods:
- GET, POST, OPTIONS
Access-Control-Allow-Origin:
- '*'
Access-Control-Expose-Headers:
- Content-Length,Content-Type,Date,Server,Connection
Connection:
- keep-alive
Content-Length:
- '284'
Content-Type:
- application/json
Date:
- Thu, 09 Feb 2023 05:52:39 GMT
Server:
- nginx/1.18.0
Strict-Transport-Security:
- max-age=31536000; includeSubDomains; preload
status:
code: 200
message: OK
version: 1
23 changes: 23 additions & 0 deletions tests/test_message.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import pytest

from click.testing import CliRunner
from telegram_cli.cli import cli


env = {
"TELEGRAM_TOKEN": "1234567890abcdef1234567890abcdef", # fake token for testing
}


@pytest.mark.vcr
@pytest.mark.block_network
def test_send():
runner = CliRunner()
with runner.isolated_filesystem():
result = runner.invoke(
cli,
["message", "send", "--text", "'Hello, world!'", "--chat-id", "161035319"],
env=env,
)
assert result.exit_code == 0
assert "message-id: 665" in result.output

0 comments on commit 00dd87e

Please sign in to comment.