raremaxim / cloudapi Goto Github PK
View Code? Open in Web Editor NEWLibrary for working with many API in Delphi
Home Page: https://t.me/CloudAPI
License: Other
Library for working with many API in Delphi
Home Page: https://t.me/CloudAPI
License: Other
The demos are not complete.
Plz fill the empty places . And make more clear how to use the demo program.
I downloaded TelegAPI and tried to complile it by hitting F9, but Delphi told me that the DJSON_Project package could not be found. Google didn't help me, so I wanted to ask, where do I get this DJSON_Project from?
Нет ли у Вас мыслей портировать для Lazarus
class:
...
[Alias('successful_payment')]
SuccessfulPayment: TtgSuccessfulPayment;
end;
.....
destructor TtgMessage.Destroy;
begin
FreeAndNil(From);
FreeAndNil(Chat);
FreeAndNil(ForwardFrom);
FreeAndNil(ForwardFromChat);
FreeAndNil(ReplyToMessage);
FreeAndNil(Audio);
FreeAndNil(Document);
FreeAndNil(Sticker);
FreeAndNil(Video);
FreeAndNil(Voice);
FreeAndNil(Contact);
FreeAndNil(Location);
FreeAndNil(Venue);
FreeAndNil(LeftChatMember);
FreeAndNil(PinnedMessage);
FreeAndNil(ForwardFromChat);
FreeAndNil(NewChatMember);
FreeAndNil(NewChatMembers);
FreeAndNil(Photo);
FreeAndNil(Entities);
FreeAndNil(NewChatPhoto);
FreeAndNil(Game);
inherited Destroy;
end;
i installed this package today and ran the EchoBot demo
but when i send /help to bot , most of the time bot is crashed and log :
Access violation at address 004080F2 in module 'EchoBot.exe'. Read of address 40878908
i trace the code and find a clue
program crashed in function TTelegramBot.ParamsToFormData
at line 1837 LTest := dj.From(LParameter.Value, TJsonUtils.DJsonConfig(True)).ToJson;
but when i trace more i seen the main problem
you used DJSON written by @mauriziodm , in line DJSON.pas in function TdjValueDestination.ToJSON: String;
line 885 Result := FParams.GetEngineClass.Serialize(FValue, nil, FParams);
crash point is here
i just fixed it with change function TdjValueDestination.ToJSON: String;
and add sleep(500)
to function
function TdjValueDestination.ToJSON: String;
begin
try
sleep(500);
Result := FParams.GetEngineClass.Serialize(FValue, nil, FParams);
finally
Self.Free;
end;
end;
Not an issue
Sends a message as soon as someone joins a group where the bot is in.
Does nothing.
I'm not sure how I can do this. Any ideas?
Добрый день. Как воспользоваться методом для отправки фото. Можно пример?
Hi,
TelegaPi.Types.pas isn't included in the GIT repo.
Все параметры этой функции перекрывают друг друга:
/// <param name="ChatId">
/// Required if InlineMessageId is not specified. Unique identifier for <br />
/// the target chat or username of the target channel (in the format <br />
/// @channelusername) <br />
/// </param>
/// <param name="MessageId">
/// Required if InlineMessageId is not specified. Unique identifier of <br />
/// the sent message <br />
/// </param>
/// <param name="InlineMessageId">
/// Required if ChatId and MessageId are not specified. Identifier of <br />
/// the inline message <br />
/// </param>
Поэтому имеет смысл сделать три перегрузки этой фукнции, по одной на каждый параметр.
Для всех клавиатур выставляемые параметры Контакты и Локация ни на что не влияют.
Сейчас выполнение треда обновления имеет как минимум три узких места, из-за которого его завершение может приводить к долгому ожиданию и даже Access Violation.
Предлагаю оптимизировать выполнение предусловием, вместо постусловия, а также с помощью Queue. Разумеется, этот вариант не предел мечтаний и его нужно тщательно проверить, но часть проблем он решает.
procedure TtgRecesiver.Execute;
var
LUpdates: TArray<TtgUpdate>;
begin
if Assigned(Bot.OnConnect) then
Bot.OnConnect(Bot);
repeat
try
LUpdates := FBot.GetUpdates(Bot.MessageOffset, 100, 0, UPDATES_ALLOWED_ALL);
except
on E: Exception do
FBot.ErrorHandler(E);
end;
if Length(LUpdates) > 0 then
begin
Bot.MessageOffset := LUpdates[High(LUpdates)].Id + 1;
if Terminated then Exit;
TThread.Queue(nil,
procedure
var
I: Integer;
begin
for I := Low(LUpdates) to High(LUpdates) do
Self.OnUpdateReceived(LUpdates[I]);
if Assigned(LUpdates) then
begin
for I := Low(LUpdates) to High(LUpdates) do
FreeAndNil(LUpdates[I]);
LUpdates := nil;
end;
end);
end;
Sleep(Bot.PollingTimeout);
until (Terminated) or (not Bot.IsReceiving);
end;
Функция EditMessageReplyMarkup вызывает на самом деле метод editMessageText.
function TTelegramBot.EditMessageReplyMarkup(ChatId: TValue; MessageId: Integer; ReplyMarkup: TtgReplyKeyboardMarkup): Boolean;
var
Parameters: TDictionary<string, TValue>;
begin
Parameters := TDictionary<string, TValue>.Create;
try
Parameters.Add('chat_id', ChatId);
Parameters.Add('message_id', MessageId);
Parameters.Add('reply_markup', ReplyMarkup);
Result := API<Boolean>('editMessageText', Parameters);
finally
Parameters.Free;
end;
end;
Hello good afternoon, install the component without problems, using a form I use TelegramBot1, including the Token of my BOT, I put the following code and send me Error, could you use an example of how to use a simple form to send a message to a group? Having already the group ID
Try to attach sample but i cant
My simple code
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, TelegAPI.Bot;
type
TForm1 = class(TForm)
Button1: TButton;
TelegramBot1: TTelegramBot;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
XSuperObject;
procedure TForm1.Button1Click(Sender: TObject);
begin
try
ShowMessage(TelegramBot1.getMe.Username);
except
ShowMessage('Error');
end;
TelegramBot1.Free;
end;
end.
Удалить файлы из репозитория, которые RAD Studio создает сама
Как клавиатуру добавить)) неплохо бы примерчик хороший
Добавить новые поля
/help
SendDataToServer@Access violation at address 0045C6DC in module 'EchoBot.exe'. Read of address FFFFFFB9
RequestAPI@Can't parse response
Все работает!!! Спасибо
TelegAPI.Types
Helo ms301, can you translate your github text from Russian to English?
Thank you.
regards
delphifocus
Сейчас получение обновлений выполняется синхронно, каждый раз требующее сначала обработать все обновления предыдущего этапа, прежде чем произойдёт чтение следующего. Если выполнение любого действия займёт достаточно много времени, то это время придётся ждать всем пользователям бота, прежде чем он отреагирует на их запрос.
В Indy, к примеру, все запросы в серверные компоненты (IdHTTPServer, например) потоконебезопасные именно по этой причине - чтобы обработка была максимально быстрой. Если нужно обновить элементы UI, то лучше использовать TThread.Synchronize. Но в случае с ботом гораздо практичнее запускать его в консоли или службе, поэтому требования к потокобезопасности заметно ниже.
Сейчас потоконебезопасный обработчик закрыт в {$IF Defined(NO_QUEUE)}, но куда эффективнее было бы завести свойство Async в родительском компоненте, в зависимости от значения которого будет выбираться первый или второй обработчик.
Пример (учитывая, что FASync выведено в переменные потока):
procedure TtgRecesiver.Execute;
var
LUpdates: TArray<TtgUpdate>;
I: Integer;
begin
if Assigned(Bot.OnConnect) then
Bot.OnConnect(Bot);
repeat
try
LUpdates := FBot.GetUpdates(Bot.MessageOffset, 100, 0, Bot.AllowedUpdates);
except
on E: Exception do
FBot.ErrorHandler(E);
end;
if Length(LUpdates) > 0 then
begin
Bot.MessageOffset := LUpdates[High(LUpdates)].ID + 1;
for I := Low(LUpdates) to High(LUpdates) do
begin
if FASync then
Self.OnUpdateReceived(LUpdates[I])
else
TThread.Synchronize(nil,
procedure
begin
Self.OnUpdateReceived(LUpdates[I]);
end);
FreeAndNil(LUpdates[I]);
end;
end;
Sleep(Bot.PollingTimeout);
until (Terminated) or (not Bot.IsReceiving);
end;
Добавить новые методы
для управления группами и каналами.
Предлагаю добавить методы START и STOP.
Длинное слово ISReceiving, означающее "приём, принимаю" заменить на Active.
Бот ещё же и отправляет инфу.
пример кода:
form.OnDestroy;
begin
...
if tgBot.Active then tgBot.Stop;
...
end;
Сравните с тем, что сейчас:
if tgBot.isReceiving then tgBot.isReceiving:=false;
unfortunately, There is some issue on JsonDataObjects.TJsonDataValue class, and we can not to use this package
Может в тестовом Эхоботе мемо сделать read only?
Для динамического создания клавиатур имеет смысл создать прототип конструктора, не требующий обязательной передачи массива клавиш или готовой клавиатуры. Сейчас можно вызвать его с пустым значением, но это приведёт к Access Violation.
Чтобы удобно использовать конструкции вроде такой:
Keyboard := TtgReplyKeyboardMarkup.Create(True, False);
with Keyboard do
begin
AddRow([...]);
...cледует расширить перегрузки конструкторов клавиатур:
constructor TtgReplyKeyboardMarkup.Create(AResizeKeyboard, AOneTimeKeyboard: Boolean);
begin
inherited Create;
ResizeKeyboard := AResizeKeyboard;
OneTimeKeyboard := AOneTimeKeyboard;
end;
constructor TtgInlineKeyboardMarkup.Create;
begin
inherited Create;
end;
Нет ли у Вас мыслей портировать для Lazarus?
Максим, здравствуйте!
Хочется сказать спасибо, за библиотеку TelegramBot для Delphi.
Классная вещь! А вы отмечали что происходит утечка памяти если зациклить методы getUpdates или getMe? Все что подхватывает TelegramBot.API
(с) Roman Chaplyankov
Bot stops the listening thread if the connection to the Internet is broken. This causes the OnDisconnect event to be raised. It would be correct to allow users to decide whether to stop receiving messages inside the OnDisconnect event handler or continue listening until the connection is restored.
Вызываю метод, аналогично SendFoto в примерах: tgBot.SendVideo(theChatID,TtgFileToSend.FromFile('c:\testmp4\test.mp4'));
Получаю: OnGlobalException: RequestAPI@Could not convert variant of type (UnicodeString) into type (Double)
Как собрать под андроид????
helo, i have problem if my network on vpn.
error message like this:
error Execution of request terminated with unknown error
but if my network not in vpn telegAPI goes well.
how to resolve error?
Желательно, чтобы демо Echobot было полноценное и демонстрировала использование всех доступных методов, который предоставляет tgBot....
Chat ID при компиляции бота под win32 или win64 определяется неверно, как 32-битный integer вместо int64.
Ошибка в функции
TdjEngineJDO.DeserializeInt(const AJSONValue: PJsonDataValue; const AValueType: TRttiType): TValue;
begin
if not Assigned(AJSONValue) or (AJSONValue.Typ = TJsonDataType.jdtNone) then
Result := 0
else
_// нужно так:_
**If AValueType.TypeKind=tkInt64 then Result := AJSONValue.LongValue** else Result := AJSONValue.IntValue;
end;
Кроме того, при компиляции под win64 ошибка в TdjEngineJDO.DeserializeArray. Нужно задавать LArrayLen: nativeint; вместо LArrayLen: Longint;
В методе SendDocument при отправке файла из потока, например html из TStringStream нужно сохранить имя файла, чтобы на принимающей стороне пришел файл именно с заданным именем и расширением. В конструкторе Create для поточных файлов нужно тоже задавать FileName.
а потом подсовывать его вместо имени временного файла при вызове API SendDocument.
The Demo program uses the token.inc that wasn't in the project. Can you attach the file please?
Thanks in advance
I've tried TelegAPI and I am excited so far. Good job.
But there is one thing I still dont get: When I choose "EchoBot.exe" and compile it, it runs without problems, also editing the source code to send/receive different stuff works fine, but when I try to edit the GUI (by clicking on the EchoBot.Main.fmx inside the projectmanager) then it throws an error like this:
Class TTelegramBot not found. Ignore the Error and continue? WARNING: Ignoring the error may result in components or propertys getting lost/deleted. [ignore] [abort] [ignore all]
If I click on [ignore] it comes up with another error, saying the class "TTgBotRecesiverUI" is missing too - so same error with another class.
If I ignore the warnings I can edit the fmx GUI controls, but then some (many) things in the source code won't work of course and if I abort the error(s), then I can't edit the GUI.
So my question is:
Where do I get these missing classes class from? Or how can I otherwise edit the GUI by ensuring the code will still work?
Добавить новые методы
для управления пользователями и админами
Добавить новый параметр until_date в метод kickChatMember для бана по времени
EditMessageReplyMarkup, SendPhoto и другие функции имеют тип параметра "ReplyMarkup: TtgReplyKeyboardMarkup", тогда как по логике должны быть TtgInlineKeyboardMarkup. Простая замена типа параметра - и функция начинает работать правильно, выводя клавиатуру.
Неплохо было бы вообще привести тип к интерфейсному IReplyMarkup, но нужно быть осторожным, во избежание ошибок "Invalid pointer operation".
Yes or No?
Пытаюсь использовать внутри DLL, ошибок никаких не выдаёт, но процедура, в которой должны обрабатываться получаемые ботом сообщения, просто не вызывается. Демки работают корректно.
This type TTelegaReplyKeyboardMarkup is from any unit outside from git?
Параметр InlineMessageId в функции должен задаваться только при отсутствии ChatId и MessageId, иначе приводит к ошибке 400. Нужно создать два overload варианта.
Полагаю, та же проблема у всех функций с параметром InlineMessageId.
Not an issue but I was wondering how can I change the bot profile picture?
Добавить новые поля
в ChatMember.
Есть публичный канал, мой бот (TelegaPi) добавлен как администратор канала и имеет все привилегии, бот пытается послать сообщение в канал, но получает:
OnApiException: TTelegramBot.ApiTest@EApiRequestException:
ErrorCode = 0. Message = {"ok":false,"error_code":400,"description":"Bad Request: chat not found"}
Хотя, скажем на версии Bot API: 3.3.0 отправка сообщения в публичный канал работала.
Метод вызывался так:
tgBot.SendMessage('-999999','Test Message');
где -999999 - это ID публичного канала
В CallbackQuery запись ACallbackQuery.InlineMessageId пуста, хотя должна содержать уникальный идентификатор сообщения.
На компьютерах, где по какой-то причине каталог Bin от Delphi не попал в переменную Path, при попытке собрать пакет появляется ошибка "brcc32 exited with code 9009", после чего сборка завершается. Причина в командах "до сборки", где brcc32 вызывается без пути к файлу. Чтобы проект успешно собирался, предлагаю заменить команду на полный прототип:
"$(BDS)\Bin\brcc32.exe" -fo "$(PROJECTDIR)\TTelegramBot.dcr" "$(PROJECTDIR)\TTelegramBot.rc"
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.