Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/reference/chat.md
Original file line number Diff line number Diff line change
Expand Up @@ -1617,7 +1617,7 @@ Partial: `groups-channels-admin.admin-list`

Remove (kick) a member; they can rejoin.

A kick is `editBanned(view_messages)` followed by an empty mask, so the person may come back. Use `chat member ban` to keep them out. `--purge` drains `messages.affectedHistory` until the server stops handing back an offset.
A kick is `editBanned(view_messages)` followed by an empty mask, so the person may come back. Use `chat member ban` to keep them out. In a channel or supergroup the member is looked up first: someone already banned stays banned and someone not in the chat is left alone (`already: true`). Naming this account is refused (use `chat leave`), and if the unban step fails the error says they are now banned. `--purge` drains `messages.affectedHistory` until the server stops handing back an offset.

```
tlgr chat member remove <CHAT> [USER]... [OPTIONS]
Expand Down
4 changes: 2 additions & 2 deletions docs/reference/contact.md
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ Full: `contacts-users.close-friends-set`, `stories.close-friends-set`

Bulk-import a phonebook from vCard or CSV.

Heavily flood-limited, so imports are chunked (`--batch-size`, 200 by default) and paced by the session limiter. `popular_invites` says how many other people already imported that number.
Heavily flood-limited, so imports are chunked (`--batch-size`, 200 by default) and paced by the session limiter. `popular_invites` says how many other people already imported that number. Numbers must be international (+ and country code): a row that is not is skipped and listed in `rejected`, never guessed at.

```
tlgr contact import <FILE> [OPTIONS]
Expand Down Expand Up @@ -560,7 +560,7 @@ Full: `contacts-users.contacts-statuses`, `dialogs.presence-watch`

Two-way sync of a local phonebook file with the server contact list.

Prints the diff and changes nothing unless `--apply` is given, because `contacts.deleteByPhones` is irreversible server-side.
Prints the diff and changes nothing unless `--apply` is given, because `contacts.deleteByPhones` is irreversible server-side. Rows whose number is not international (+ and country code) are listed in `rejected`; with --delete-missing they make --apply refuse, since a skipped row may be a contact the diff would delete.

```
tlgr contact sync <FILE> [OPTIONS]
Expand Down
2 changes: 1 addition & 1 deletion docs/reference/message.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ Composing a rich body needs layer 229 and is refused with NOT_SUPPORTED.

Delete messages for me or for everyone.

In a channel or supergroup a delete is always for everyone — `channels.deleteMessages` has no revoke flag — so --for-me is only meaningful in private chats and basic groups.
In a channel or supergroup a delete is always for everyone (`channels.deleteMessages` has no revoke flag), so --for-me is only meaningful in private chats and basic groups. There, Telegram deletes by bare id across the whole account, so each id is first checked to be a message of CHAT: a typed id that is not is refused and nothing is deleted; ids from a range that are not are skipped and listed in `skipped`.

```
tlgr message delete <CHAT> [MSG_ID]... [OPTIONS]
Expand Down
2 changes: 1 addition & 1 deletion docs/reference/resolve.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ Full: `contacts-users.peer-id-conversion`, `dialogs.resolve-peer`

Resolve a phone number to a user without adding a contact.

PHONE_NOT_OCCUPIED exits 13, never 5: no account and a privacy refusal are indistinguishable from here. The server asks for at most one lookup every three seconds, so --offline formats and validates against help.getCountriesList without an RPC.
PHONE_NOT_OCCUPIED exits 13, never 5: no account and a privacy refusal are indistinguishable from here. The server asks for at most one lookup every three seconds, so --offline formats and validates against help.getCountriesList without an RPC. The number must be international (+ and country code); a local form such as 0912... is refused rather than given a guessed country code.

```
tlgr resolve phone <PHONE> [OPTIONS]
Expand Down
19 changes: 16 additions & 3 deletions tests/fake_telethon.py
Original file line number Diff line number Diff line change
Expand Up @@ -1294,6 +1294,9 @@ def add_call_log_entry(
action=action,
)
self.call_log.append(message)
# A call is a service message in the DM too, which is what lets
# `call log delete` check the id belongs to that chat.
self.history(chat_id).append(message)
return message

# -- the administration world ------------------------------------------
Expand Down Expand Up @@ -4846,9 +4849,19 @@ async def edit_message(self, entity: Any, message: Any, text: str = "", **kwargs
async def delete_messages(self, entity: Any, message_ids: Any, revoke: bool = True) -> Any:
chat_id = self._chat_id(entity)
wanted = {int(i) for i in ([message_ids] if isinstance(message_ids, int) else message_ids)}
history = self.world.history(chat_id)
removed = [m for m in history if m.id in wanted]
self.world.messages[chat_id] = [m for m in history if m.id not in wanted]
# Like Telegram: a channel numbers its own messages and
# `channels.deleteMessages` honours it, but for any other peer
# Telethon sends `messages.deleteMessages(id=[...])` with no peer, and
# the ids are account-wide: whatever chat holds them loses them.
if chat_id <= -1000000000000:
scope = [chat_id]
else:
scope = [c for c in self.world.messages if c > -1000000000000]
removed = []
for chat in scope:
history = self.world.history(chat)
removed.extend(m for m in history if m.id in wanted)
self.world.messages[chat] = [m for m in history if m.id not in wanted]
self.world.calls.append(
("delete_messages", {"chat_id": chat_id, "ids": sorted(wanted), "revoke": revoke})
)
Expand Down
47 changes: 47 additions & 0 deletions tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,53 @@ def test_user_ref_rejects_a_channel_id(self):
def test_user_ref_accepts_a_user(self):
assert parse_user_ref("+989120000000").kind == "phone"

def test_a_phone_ref_with_a_zero_country_code_is_refused(self):
with pytest.raises(ValueError, match="never starts with 0"):
parse_peer_ref("+0912 345 6789")


class TestParseE164:
"""Typed phones: international form only, never a guessed country code."""

@pytest.mark.parametrize(
("text", "value"),
[
("+98 912 345 6789", "+989123456789"),
("+1 (212) 555-1234", "+12125551234"),
("+44.20.7946.0018", "+442079460018"),
(" +7 916 123-45-67 ", "+79161234567"),
("+۹۸ ۹۱۲ ۳۴۵ ۶۷۸۹", "+989123456789"),
("‎+98 912 345 6789‏", "+989123456789"),
("+683 4002", "+6834002"),
],
)
def test_accepts_international_numbers(self, text, value):
from tlgr.models.peer import parse_e164

assert parse_e164(text) == value

@pytest.mark.parametrize(
("text", "why"),
[
# The issue's two misdirections: +91 India and +212 Morocco.
("9123456789", "no country code"),
("2125551234", "no country code"),
("8 999 000-11-22", "no country code"),
("0912 345 6789", "local number"),
("0098 912 345 6789", r"\+98 ?912"),
("+0912 345 6789", "never starts with 0"),
("+12345", "7 to 15"),
("+1234567890123456", "7 to 15"),
("+98 912 abc", "not a phone number"),
("", "required"),
],
)
def test_refuses_local_and_malformed_forms(self, text, why):
from tlgr.models.peer import PhoneNumberError, parse_e164

with pytest.raises(PhoneNumberError, match=why):
parse_e164(text)

def test_peer_ref_is_a_wire_shape(self):
ref = parse_peer_ref("@alice")
assert json.loads(encode(ref)) == {"raw": "@alice", "kind": "username", "value": "alice"}
Expand Down
16 changes: 16 additions & 0 deletions tests/test_ops_call.py
Original file line number Diff line number Diff line change
Expand Up @@ -418,6 +418,22 @@ async def test_deleting_rows_takes_chat_and_id(self, live_daemon, client, in_thr
assert deleted == {"deleted": 1, "revoked": True}
assert log.called("delete_messages")[0]["ids"] == [501]

async def test_a_row_naming_another_chats_message_is_refused(
self, live_daemon, client, in_thread, log
):
"""`messages.deleteMessages` takes bare ids: 777 would go wherever it lives."""
from fake_telethon import make_user

log.add_user(make_user(4343, username="bobby"))
log.add_message(4343, "not a call", message_id=777)
error = await failure(
client, in_thread, "call.log.delete", {"id": [f"{ALICE}:501", f"{ALICE}:777"]}
)
assert error.exit_code == EXIT_NOT_FOUND
assert "777" in error.message
assert log.find(4343, 777) is not None
assert not log.called("delete_messages")

async def test_a_row_without_a_chat_is_a_usage_error(self, live_daemon, client, in_thread, log):
error = await failure(client, in_thread, "call.log.delete", {"id": ["501"]})
assert error.exit_code == EXIT_USAGE
Expand Down
81 changes: 81 additions & 0 deletions tests/test_ops_chat_admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
EXIT_INDETERMINATE,
EXIT_NOT_FOUND,
EXIT_PERMISSION,
EXIT_RATE_LIMITED,
EXIT_USAGE,
classify,
)
Expand Down Expand Up @@ -246,6 +247,86 @@ async def test_a_kick_bans_then_unbans_so_they_may_return(
assert sent[1].banned_rights.view_messages is False
assert admin_world.banned.get(GROUP_ID, {}) == {}

async def test_kicking_an_already_banned_user_does_not_unban_them(
self, live_daemon, client, in_thread, admin_world
):
"""The kick's second editBanned would otherwise lift the ban."""
await result(
client, in_thread, "chat.member.ban", {"chat": str(GROUP_ID), "user": [str(BOB)]}
)
bans = len(admin_world.called("EditBannedRequest"))
out = await result(
client, in_thread, "chat.member.remove", {"chat": str(GROUP_ID), "user": [str(BOB)]}
)
assert out == [
{"chat_id": GROUP_ID, "user_id": BOB, "removed": False, "banned": True, "already": True}
]
assert len(admin_world.called("EditBannedRequest")) == bans
assert admin_world.banned[GROUP_ID][BOB].view_messages is True

async def test_kicking_a_non_member_changes_nothing(
self, live_daemon, client, in_thread, admin_world
):
out = await result(
client, in_thread, "chat.member.remove", {"chat": str(GROUP_ID), "user": [str(CAROL)]}
)
assert out[0]["already"] is True and out[0]["removed"] is False
assert not admin_world.called("EditBannedRequest")

async def test_kicking_yourself_is_refused_before_anyone_is_removed(
self, live_daemon, client, in_thread, admin_world
):
with pytest.raises(Exception) as caught:
await call(
client,
in_thread,
"chat.member.remove",
{"chat": str(GROUP_ID), "user": [str(BOB), "me"]},
)
error = classify(caught.value)
assert error.exit_code == EXIT_USAGE
assert "chat leave" in error.message
assert not admin_world.called("EditBannedRequest")
assert BOB in admin_world.members[GROUP_ID]

async def test_kicking_yourself_by_username_is_refused_too(
self, live_daemon, client, in_thread, admin_world
):
admin_world.me.username = "myself"
admin_world.add_user(admin_world.me)
code = await fails(
client, in_thread, "chat.member.remove", {"chat": str(GROUP_ID), "user": ["@myself"]}
)
assert code == EXIT_USAGE
assert not admin_world.called("EditBannedRequest")

async def test_a_failed_unban_says_the_user_is_now_banned(
self, live_daemon, client, in_thread, admin_world
):
from telethon.errors import FloodWaitError
from telethon.tl import types

def ban_then_flood(request):
if request.banned_rights.view_messages:
admin_world.banned.setdefault(GROUP_ID, {})[BOB] = request.banned_rights
return types.Updates(updates=[], users=[], chats=[], date=None, seq=0)
raise FloodWaitError(request, capture=30)

admin_world.raw["EditBannedRequest"] = ban_then_flood
with pytest.raises(Exception) as caught:
await call(
client,
in_thread,
"chat.member.remove",
{"chat": str(GROUP_ID), "user": [str(BOB)]},
flood_wait_max=0,
)
error = classify(caught.value)
assert error.exit_code == EXIT_RATE_LIMITED
assert "BANNED" in error.message
assert f"chat member unban {GROUP_ID} {BOB}" in (error.hint or "")
assert error.wait_seconds == 30

async def test_a_ban_leaves_the_mask_in_place(
self, live_daemon, client, in_thread, admin_world
):
Expand Down
108 changes: 108 additions & 0 deletions tests/test_ops_contacts.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,19 @@ async def test_no_target_at_all_is_a_usage_error(self, live_daemon, client, in_t
await result(client, in_thread, "contact.add", {"first_name": "Nobody"})
assert classify(caught.value).exit_code == EXIT_USAGE

async def test_a_phone_without_a_country_code_is_refused_not_guessed(
self, live_daemon, client, in_thread, book
):
"""`2125551234` must not become +212 (Morocco) and import a stranger."""
with pytest.raises(Exception) as caught:
await result(
client, in_thread, "contact.add", {"phone": "2125551234", "first_name": "Al"}
)
error = classify(caught.value)
assert error.exit_code == EXIT_USAGE
assert "country code" in error.message
assert not book.called("ImportContactsRequest")


class TestContactRename:
async def test_it_writes_only_our_view_of_the_name(self, live_daemon, client, in_thread, book):
Expand Down Expand Up @@ -317,6 +330,21 @@ async def test_removing_by_phone_reaches_numbers_with_no_account(
assert answer["phones"] == ["+15550003333"]
assert book.saved_contacts == []

async def test_a_local_phone_is_refused_before_anything_is_deleted(
self, live_daemon, client, in_thread, book
):
with pytest.raises(Exception) as caught:
await result(
client,
in_thread,
"contact.remove",
{"user": ["@alice"], "phone": ["0912 345 6789"]},
)
assert classify(caught.value).exit_code == EXIT_USAGE
assert not book.called("DeleteByPhonesRequest")
assert not book.called("DeleteContactsRequest")
assert ALICE in book.contacts

async def test_nothing_to_remove_is_a_usage_error(self, live_daemon, client, in_thread, book):
with pytest.raises(Exception) as caught:
await result(client, in_thread, "contact.remove", {})
Expand Down Expand Up @@ -704,6 +732,75 @@ async def test_import_batches(self, live_daemon, client, in_thread, book, tmp_pa
)
assert answer["batches"] == 3

async def test_a_local_number_is_reported_and_the_rest_imported(
self, live_daemon, client, in_thread, book, tmp_path
):
"""`9123456789` (an Iranian mobile without its 0) is not +91 India."""
path = tmp_path / "mixed.csv"
path.write_text("phone,first,last\n+15550009999,Carol,\n9123456789,Reza,Ahmadi\n")
envelope = await call(client, in_thread, "contact.import", {"file": str(path)})
answer = envelope["result"]
assert answer["parsed"] == 1
assert [row["phone"] for row in answer["imported"]] == ["+15550009999"]
assert answer["rejected"] == [
{
"line": 3,
"value": "9123456789",
"name": "Reza Ahmadi",
"reason": answer["rejected"][0]["reason"],
}
]
assert "country code" in answer["rejected"][0]["reason"]
assert any("line 3" in w for w in envelope["meta"]["warnings"])
sent = [c.phone for r in book.called("ImportContactsRequest") for c in r.contacts]
assert sent == ["+15550009999"]

async def test_a_vcard_with_only_a_local_number_is_rejected(
self, live_daemon, client, in_thread, book, tmp_path
):
path = tmp_path / "local.vcf"
path.write_text(
"BEGIN:VCARD\nVERSION:3.0\nN:Ahmadi;Reza;;;\nTEL;TYPE=CELL:0912 345 6789\n"
"END:VCARD\nBEGIN:VCARD\nVERSION:4.0\nFN:Carol Cooper\n"
"TEL;VALUE=uri;TYPE=cell:tel:+1-555-000-9999\nEND:VCARD\n"
)
answer = await result(client, in_thread, "contact.import", {"file": str(path)})
assert [row["phone"] for row in answer["imported"]] == ["+15550009999"]
assert [(r["line"], r["name"]) for r in answer["rejected"]] == [(4, "Reza Ahmadi")]

async def test_a_file_of_only_local_numbers_is_a_usage_error(
self, live_daemon, client, in_thread, book, tmp_path
):
path = tmp_path / "local.csv"
path.write_text("09123456789,Reza\n")
with pytest.raises(Exception) as caught:
await result(client, in_thread, "contact.import", {"file": str(path)})
error = classify(caught.value)
assert error.exit_code == EXIT_USAGE
assert "line 1" in error.message
assert not book.called("ImportContactsRequest")

async def test_sync_refuses_to_delete_when_a_row_was_rejected(
self, live_daemon, client, in_thread, book, tmp_path
):
"""A skipped `0...` row may be exactly a contact --delete-missing would delete."""
path = tmp_path / "sync.csv"
path.write_text("+15550009999,Carol\n15550001111,Alice\n")
preview = await result(
client, in_thread, "contact.sync", {"file": str(path), "delete_missing": True}
)
assert [r["value"] for r in preview["rejected"]] == ["15550001111"]
with pytest.raises(Exception) as caught:
await result(
client,
in_thread,
"contact.sync",
{"file": str(path), "delete_missing": True, "apply": True},
)
assert classify(caught.value).exit_code == EXIT_USAGE
assert not book.called("DeleteByPhonesRequest")
assert ALICE in book.contacts

async def test_an_empty_file_is_a_usage_error(
self, live_daemon, client, in_thread, book, tmp_path
):
Expand Down Expand Up @@ -1261,6 +1358,17 @@ async def test_a_phone_resolves_without_adding_a_contact(
assert answer["peer"]["id"] == CAROL
assert CAROL not in book.contacts

async def test_a_phone_without_a_plus_is_refused_before_any_lookup(
self, live_daemon, client, in_thread, book
):
"""`9123456789` typed for Iran must not be looked up as +91 (India)."""
with pytest.raises(Exception) as caught:
await result(client, in_thread, "resolve.phone", {"phone": "912 345 6789"})
error = classify(caught.value)
assert error.exit_code == EXIT_USAGE
assert "country code" in error.message
assert not book.called("ResolvePhoneRequest")

async def test_an_unoccupied_phone_is_indeterminate_never_not_found(
self, live_daemon, client, in_thread, book
):
Expand Down
Loading
Loading