Telegram Username Changes: Keep the Right CRM Contact
An identity policy for custom Telegram integrations: mutable aliases, sender boundaries, a local SQLite test and a controlled migration of old records.
Telegram Username Changes: Keep the Right CRM Contact
Link a Telegram account to its CRM contact using a trusted User.id, and store the username as a changeable attribute. A new username for the same account can then update the existing contact's label. A familiar username attached to a different ID must not merge enquiry histories, unlock old documents or change the recipient of a reply.
This is a proposed policy for your own Telegram Bot API integration with a CRM. It does not describe a verified 24go.site setting or require collecting other people's phone numbers. The example accepts only ordinary incoming messages in a private chat with a bot, after delivery authentication and schema validation. It does not establish a person's legal identity, authority over a deal or permission to send marketing messages.
Separate a label, an account and a conversation
The User object defines id as the unique identifier for a user or bot. Its username is optional. First and last names are display information; even a complete name does not establish that two senders belong to the same customer.
Keep three concepts distinct. A Telegram account maps to an internal contact. A conversation records where an interaction took place. A deal represents a particular enquiry. One account can bring several enquiries, while several employees can represent one company. Your CRM process defines those relationships; a username string cannot do that work.
For a reply route, retain message.chat.id from the permitted event. Do not reconstruct the recipient from an old t.me/... link. In sendMessage, a string username in chat_id is documented for a target bot, supergroup or channel. That is not a promise that any ordinary private user can be addressed by a handle. A valid numeric route also does not, by itself, grant permission to contact someone.
The Telegram FAQ says that a username is optional and deleting it does not affect existing conversations. Collectible usernames can also be assigned to chats or transferred between owners. A unique text alias in your database is therefore not a sufficient safeguard for customer history.
Establish what the sender field represents
Do not treat any nested id in a JSON object as the person currently contacting your company. The Message field from is optional. For a message sent on behalf of a chat, sender_chat carries that context, and from can contain a fake sender user for backward compatibility.
The narrow handler in this article accepts only message.chat.type == "private", a from object containing a positive integer ID, and is_bot == false. It leaves events with sender_chat, business_connection_id or guest_query_id to another handler. These exclusions define the example's scope; they do not mean those events can never be processed.
Telegram Business and guest queries need a separate context model. The API documentation warns that their conversation can be independent of an ordinary bot chat sharing the same identifier. A common username key does not resolve that distinction. Before extending your handler, define the connection owner, access checks and reply route for each supported context.
A forwarded message or an @name mentioned in text does not change the sender of the current event either. Do not automatically attach the forwarded author's identity to the current contact. If the task is to save a phone number from a shared contact, use a separate contact ownership check.
Decide before updating a CRM record
Look up the account ID inside the correct organization namespace first. A tenant here means a separate SaaS customer or isolated project. The same Telegram ID appearing in two tenants must not automatically give their employees access to a shared CRM record.
| Observation | Integration decision | What remains protected |
|---|---|---|
| Known ID with a new username | Update the observed label | Existing internal contact and history |
| Known ID without username in a complete User object | Clear the current label or explicitly mark it absent | ID-based contact mapping |
| Different ID with a familiar username | Use a separate mapping; review any disputed business link | Separate account histories |
| No supported from or a sender_chat is present | Do not run this narrow handler | Original event for restricted investigation |
| Same Telegram ID in another tenant | Look up only inside that tenant | Project data isolation |
| Known contact with a new question | Apply the agreed deal-opening rule | Contact and deal remain separate concepts |
A missing username in a complete User object is different from a missing field in a partial CRM update. The first can mean there is no current label; the second can mean that the source did not provide a profile change. Define the adapter contract explicitly: replacement of a complete observed profile, or a partial update. Do not erase stored values whenever an arbitrary intermediate JSON object lacks a key.
A minimal data model and its conflict rules
Keep your internal contact ID separate from the Telegram ID. One possible unique key for an external identity table is (tenant_id, source, telegram_user_id), with source explicitly set to telegram. This is a proposed design for your system, not Telegram's key format. If several bots in one tenant should share contacts, agree on that access rule. Otherwise, include a bot or integration namespace.
Store the username in a field such as observed_username, together with observation time and source. If historical aliases serve a real purpose, label them as past observations that cannot select a recipient or establish the current owner. Do not give usernames a unique contact constraint, and do not use them as a fallback identity key when the ID is unknown.
The User documentation warns that an ID may exceed 32 significant bits and has at most 52 significant bits. Choose a lossless representation across the entire path: for example, a signed BIGINT in storage and an explicitly agreed representation in queue messages. If an interface uses decimal strings, validate and convert deliberately. Casting an already truncated 32-bit value later cannot restore the original identifier.
Enforce uniqueness in the database and write the mapping in a transaction. A preliminary search alone leaves a race: two handlers can both conclude that the contact does not exist. When the CRM is a separate service, a local transaction does not cover remote creation. That needs an operation protocol of its own, including repeated webhook delivery and ambiguous creation timeouts.
Run a local policy check with synthetic messages
The following example checks contact selection using SQLite. It needs Python 3 with the standard sqlite3 module. Save the block as identity_policy_test.py and run python3 identity_policy_test.py without -O, which disables assertions. The IDs and labels are synthetic. The program does not contact Telegram or a CRM, and it sends no messages.
The function assumes a previously validated message structure: chat and from, when present, must be objects. It also rejects several unsupported contexts, but it is not a general-purpose parser for arbitrary JSON or a webhook authentication check. The server supplies the tenant from trusted configuration; never derive it from customer text.
import copy
import json
import sqlite3
def bind(db, tenant, message):
if message.get("chat", {}).get("type") != "private":
return None
if any(message.get(k) is not None for k in (
"sender_chat", "business_connection_id", "guest_query_id"
)):
return None
user = message.get("from", {})
uid = user.get("id")
if type(uid) is not int or uid <= 0 or user.get("is_bot") is not False:
return None
username = user.get("username")
if username is not None and not isinstance(username, str):
return None
with db:
db.execute(
"INSERT INTO identity(tenant, source, uid, username) "
"VALUES (?, 'telegram', ?, ?) "
"ON CONFLICT(tenant, source, uid) DO UPDATE "
"SET username=excluded.username",
(tenant, uid, username),
)
row = db.execute(
"SELECT contact_id FROM identity "
"WHERE tenant=? AND source='telegram' AND uid=?",
(tenant, uid),
).fetchone()
return row[0]
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE identity (contact_id INTEGER PRIMARY KEY, "
"tenant TEXT NOT NULL, source TEXT NOT NULL, uid INTEGER NOT NULL, "
"username TEXT, UNIQUE(tenant, source, uid))")
base = {"chat": {"type": "private", "id": 1001},
"from": {"id": 1001, "is_bot": False, "username": "sample_old"}}
a = bind(db, "tenant-a", base)
renamed = copy.deepcopy(base)
renamed["from"]["username"] = "sample_new"
assert bind(db, "tenant-a", renamed) == a
removed = copy.deepcopy(base)
del removed["from"]["username"]
assert bind(db, "tenant-a", removed) == a
assert db.execute("SELECT username FROM identity WHERE contact_id=?",
(a,)).fetchone()[0] is None
other = copy.deepcopy(base)
other["from"]["id"] = 2002
other["chat"]["id"] = 2002
b = bind(db, "tenant-a", other)
c = bind(db, "tenant-b", base)
assert len({a, b, c}) == 3
for field in ("sender_chat", "business_connection_id", "guest_query_id"):
unsupported = copy.deepcopy(base)
unsupported[field] = {} if field == "sender_chat" else "TEST"
assert bind(db, "tenant-a", unsupported) is None
no_id = copy.deepcopy(base)
del no_id["from"]["id"]
assert bind(db, "tenant-a", no_id) is None
group = copy.deepcopy(base)
group["chat"]["type"] = "supergroup"
assert bind(db, "tenant-a", group) is None
assert db.execute("SELECT COUNT(*) FROM identity").fetchone()[0] == 3
print(json.dumps({"contacts": 3, "rename_same_contact": True,
"missing_username_same_contact": True,
"alias_reuse_separate": True, "tenants_separate": True,
"unsupported_rejected": True}))
A successful run prints contacts: 3 and all five check flags as true. The three rows represent the original account, another account with the same synthetic label, and a mapping inside another tenant. A missing username becomes SQL NULL while the first contact's internal ID stays unchanged.
This checks the proposed policy in one process's in-memory database. It does not establish concurrent HTTP behavior, your CRM's behavior, the current owner of a real alias or Telegram authentication. In this demonstration, contact_id also serves as the identity row's internal key. A production CRM will usually have separate contact and external identity tables. If an AssertionError appears, locate the branch that changed before removing or weakening a check.
Migrate old username-keyed records without guessing
Do not start a bulk merge because an old and a new record have similar labels. Back up the data first, then build a proposed mapping table without changing the CRM. Give every proposed link an evidence category: a trusted event, an existing verified mapping, or manual investigation required. A username from an old CSV is not sufficient evidence by itself.
- Identify records that already have a verified Telegram ID. Check its type and source, then group conflicts within each tenant. Two CRM contacts mapped to one account require a process owner's decision, not selection of whichever record a search returns first.
- Leave username-only records unverified. When a new incoming message arrives, find or create the ID-based mapping, but do not attach old history just because the label looks familiar. If access to earlier orders is required, use a separate permitted customer verification process.
- Check proposed mappings against a copy. Record unsupported links, conflicts and reply-route changes. An unprocessed list is not a successfully migrated customer database.
- Apply approved mappings in bounded batches with old and new keys in the change log. Repeating a batch should not perform a fresh merge. Its rollback should undo only changes that belong to that batch.
- Keep an old username as a restricted historical observation only if there is a retention purpose. After cutover, disable the old index's ability to select recipients or unlock documents on its own.
For account deletion and a later signup, the Telegram FAQ describes the person as a new user. A new ID must not automatically be treated as proof of continuity with a previously verified customer. A similar name, photo or message saying “it is me again” can start verification; it cannot authorize disclosure of archived records.
Verify the actual integration separately
Run acceptance tests with a test bot, a test CRM and consenting participants. The SQLite output above does not establish any of the following results. For each case, retain time, selected branch and internal test record references without bot tokens or full conversations.
Start with an incoming private message. Then change or remove the same test account's displayed username and send another message. The internal mapping and permitted history should remain, while the label should reflect the latest eligible observation. Account for delayed events: a stale profile sitting in a queue must not unconditionally replace a newer observation. You need a profile-version policy and a tie-breaking rule for equal timestamps; the demonstration does not implement either.
Use isolated fixtures to test two different IDs carrying the same synthetic label, and one ID appearing in different tenants. In the latter case it may be the same Telegram account, but employee access and project CRM data must remain separate. The former case does not require acquiring somebody else's real username.
Pass unsupported contexts, redeliver an event and simulate a failure during remote contact creation. Expect the narrow identity route to refuse unsupported contexts, repeats to avoid an extra effect, and an ambiguous operation to stop for reconciliation. The older Telegram-to-CRM integration guide includes a suggestion to search for duplicates by username. That suggestion does not fit the identity policy here: a label must not decide who owns customer history. Verify your specific CRM's guarantees separately.
Account identity is not customer authorization
A Telegram ID helps distinguish technical accounts in permitted events. It does not verify an employee's authority to act for a company, ownership of an order, a phone number or access to private files. Check authorization before each protected action using the current customer link and operator role.
Define why IDs and observed aliases are retained, how long they are kept, and which employees can access them. Do not collect name histories from third-party lookup databases merely to fill CRM fields. The absence of a username is not a reason to demand unnecessary personal data. A technical contact mapping does not confer permission for advertising or unsolicited messaging.
For a project using 24go.site, put these requirements in the integration brief first, then verify the actual supported features and connection permissions. Begin migration with a copy and a conflict report. A correct label update should preserve the account mapping without expanding access to another account's history.
Sources
- Telegram Bot API: User - account ID, optional username and identifier storage precision.
- Telegram Bot API: Message - from, sender_chat, Business and guest context.
- Telegram Bot API: sendMessage - separate role of chat_id and username targets.
- Telegram FAQ: usernames and t.me - optional names, deletion and collectible aliases.
- Telegram FAQ: account deletion - signing up again as a new user.