簡體   English   中英

Telegram Bot 如何從頻道或群組中刪除或刪除消息或媒體

[英]Telegram Bot How to delete or remove a message or media from a channel or group

我想知道刪除消息或文件(如照片)的示例

我沒有找到任何這方面的功能教程,

Telegram Bot API 目前沒有這樣的功能。

UPD 2017-05-19:有一個官方方法deleteMessage ,更多信息: https ://core.telegram.org/bots/api#deletemessage

https://stackoverflow.com/a/43965602/1140438

Bot API 3.0 官方支持deleteMessage方法。 更多細節在這里: https ://core.telegram.org/bots/api#deletemessage

https://api.telegram.org/botTOKEN/deleteMessage?chat_id=CID&message_id=MID

如您所見,有兩個參數: chat_idmessage_id

您可以刪除 bot 的消息或其他消息(如果 bot 是管理員),但服務消息(例如加入/離開消息)除外。

  1. 成功時,它將返回以下 JSON 對象: {"ok":true,"result":true}

  2. 如果您嘗試刪除服務消息或其他用戶的消息,但機器人不是管理員: {"ok":false,"error_code":400,"description":"Bad Request: message can't be deleted"}

  3. 如果您嘗試刪除不存在的消息或已刪除的消息: {"ok":false,"error_code":400,"description":"Bad Request: message to delete not found"}

您可以轉發消息並保存消息 ID,然后刪除該消息。 如果你能做到,你的信息就存在。

這樣做:

try:
   mes=bot.forward_message(chat_id=?,from_chat_id=?,message_id=?)
   bot.delete_message(chat_id=?,message_id=mes.id)
except:
   print("your message deleted")

bot api 中有兩種方法可以讓您編輯消息: editMessageTexteditMessageCaption 這並不理想,但您可以將其用作替代方案。

例如,通過將消息編輯為:

“此消息不可用。”

請檢查下面的代碼片段!,下面的代碼對我有用!
String chatId = String.valueOf(callbackQuery.getMessage().getChatId());
Integer messageId = callbackQuery.getMessage().getMessageId();
DeleteMessage deleteMessage = new DeleteMessage(chatId, messageId);
try {
  execute(deleteMessage);
}catch(TelegramApiException tae) {
  throw new RuntimeException(tae);
}

使用python ,如果你有一個CommandHandler()你可以像這樣讀取chat_idmessage_id

dispatcher.add_handler(CommandHandler("start", handler_start))

def handler_start(update: Update, context: CallbackContext):
    chat_id = update.message.chat_id
    message_id = update.message._id_attrs[0]
    context.bot.delete_message(chat_id, message_id)

如果在 php 上。 我發消息。 從中獲取響應(機器人的消息 id)並使用 deleteMessage

<?php
$botToken = "yourBotToken";
$botAPI = "https://api.telegram.org/bot" . $botToken;

$update = json_decode(file_get_contents('php://input'), TRUE);
$msg = $update['message']['text'];
if ($msg == '/start') {
$data = http_build_query([
        'text' => "test message (delete this)",
        'chat_id' => $update['message']['chat']['id'],
]);
$send = file_get_contents($botAPI . "/sendMessage?{$data}");

$response = json_decode($send), true); // decode response
$message_id = $response['result']['message_id']; // get bots message

// Deleting message
$data_del = http_build_query([
    'chat_id' => $update['message']['chat']['id'],
    'message_id' => $message_id,
]);
    file_get_contents($botAPI . "/deleteMessage?{$data_del}");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM