#include <stdio.h>
#include <curl/curl.h>
int main(void) {
CURL *curl;
CURLcode response;
char* token = "wont post my bot token here";
char* channel_id = "2041832290";
char* url;
sprintf(url, "https://api.telegram.org/bot%s/sendMessage", token);
char post_fields[100];
sprintf(post_fields, "chat_id=%s&text=%s", channel_id, "Hello");
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_fields);
response = curl_easy_perform(curl);
curl_easy_cleanup(curl);
if (response != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(response));
}
}
printf("%s", response);
return 0;
}
机器人具有管理员权限,在我的电报频道中,我检查了channel_id是否正确300次,我没有任何错误,机器人似乎没有发送任何消息
我不太擅长 C/C++,但我注意到的一些关键缺失部分是:
char* url
在使用前未初始化或分配内存空间。您可以尝试以下代码吗:
#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>
int main(void)
{
CURL *curl;
CURLcode response;
char *token = "BOT_TOKEN";
char *channel_id = "CHANNEL_ID";
// Allocate memory for url
char *url = (char *)malloc(256);
sprintf(url, "https://api.telegram.org/bot%s/sendMessage", token);
char post_fields[100];
sprintf(post_fields, "chat_id=%s&text=%s", channel_id, "Hello");
curl = curl_easy_init();
if (curl)
{
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_fields);
response = curl_easy_perform(curl);
curl_easy_cleanup(curl);
if (response != CURLE_OK)
{
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(response));
}
}
// Free dynamically allocated memory
free(url);
return 0;
}
我是这样运行的:
gcc bot.c -o main -lcurl && ./main
希望这有帮助!