Telegram Automation

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
User avatar
SL5
Posts: 879
Joined: 12 May 2015, 02:10
Contact:

Re: Whatsapp & Telegram Automation

Post by SL5 » 11 Jan 2019, 05:56

gregster wrote:
11 Jan 2019, 00:59
SL5 wrote:
08 Jan 2019, 05:29
There is a solution via bookmarklets that can be combined with a fast mouse to get the username. some of the official browsers seemingly support only one solution via the mouse. Years ago, it was also possible on the keyboard .
if you are interested ... here is an undocumented without instruction: https://github.com/sl5net/global-Intell ... legram.ahk
Yes, thank you, I will have a look...
So, this is for the Desktop app, right? What info are you extracting there? Username of the last message? And/or the message itself?
I take only the username put it into a title, so its a adapter to my gi-tool

Code: Select all

WinSetTitle, ahk_class Qt5QWindowIcon,...

blue83
Posts: 157
Joined: 11 Apr 2018, 06:38

Re: Whatsapp & Telegram Automation

Post by blue83 » 25 May 2020, 03:32

Hi @gregster ,

For reading messagers I only get " {"ok":true,"result":[]}" as a result.

Can you post a code just for reading messages, because for sending there is no problem.

And maybe to read only new messages?

Thanks,
Blue

gregster
Posts: 8886
Joined: 30 Sep 2013, 06:48

Re: Whatsapp & Telegram Automation

Post by gregster » 25 May 2020, 05:17

Hi blue83, in general, the code should already be there in these two posts: here and here.

Which code are you currently using? It helps to know what we are actually talking about... and I might be able to spot problems in your code.

blue83 wrote:
25 May 2020, 03:32
For reading messagers I only get " {"ok":true,"result":[]}" as a result.

Can you post a code just for reading messages, because for sending there is no problem.
Well, that response looks promising. You seem to have a valid connection to your bot's messages.

This particular response usually means that there were no (new, unconfirmed) messages from users.
To be clear, a user (for example, you) needs to actually type in a message into the chat with the bot. It won't return the messages you sent via your bot to a user - or yourself (you should keep track of these yourself).

A very basic test script (that should show - also repeatedly - the same first 5 messages you got in the last 24 hours in a msgbox; for testing, it doesn't use an offset to ignore "old" messages - we'll get to that later). Don't forget to add your bot token:

Code: Select all

; #include json.ahk					; include to process JSON strings as objects

token := "your bot token here"

q::		; press q to get updates
update := GetUpdates(token, , 5)				; limit result to five messages
msgbox % update
; oUpd := JSON.Load(update)		; load JSON response string as an AHK object
return

Esc::ExitApp

GetUpdates(botToken, offset="", updlimit=100, timeout=0){							
	If (updlimit>100)
		updlimit := 100
	; Offset = Identifier of the first update to be returned.
	url := "https://api.telegram.org/bot" botToken "/getupdates?offset=" offset "&limit=" updlimit "&timeout=" timeout
	updjson := URLDownloadToVar(url)					
	return updjson
}

URLDownloadToVar(url,ByRef variable=""){			
	try
	{	
		hObject:=ComObjCreate("WinHttp.WinHttpRequest.5.1")
		hObject.Open("GET",url)
		hObject.Send()
		variable:=hObject.ResponseText
		return variable
	}
}
Type a few messages into your chat with the bot, and press q to get updates.

blue83 wrote:
25 May 2020, 03:32
And maybe to read only new messages?
For this, you would use the offset parameter:
gregster wrote:
29 Dec 2017, 07:54
The offset parameter is useful to tell Telegram to not deliver the same messages over and over to you. The latest offset you can get from actually parsing the JSON response and then use it for your next Update call.
To get the correct (latest) offset you actually need to parse the messages - and use the most recent update_id plus 1 in your next update call, iirc. With this, all messages with update_ids lower than that offset are "confirmed" and won't show up anymore in future updates.

I have shown this some time ago, among other things, in the code in this post. Did you try it?
Please note that you should also add your personal chat id to that code to make it work (because I restricted it to known users; of course, you can modify/remove this restriction). If you don't know your own chat ID, you can use the script above to determine it. Type a message and use the from.id part from the json string in the msgbox. But if you were already sending messages, that's probably clear.

This code parses new messages for known strings like Command1, Command2 and and reacts/runs code based on these messages/commands. Of course, you can also process these messages in other ways...

Try to type Command1 or use one of the cutom keyboard buttons... and the bot will give some (very simple :D ) feedback:

telegrambot example.png
telegrambot example.png (10.4 KiB) Viewed 3837 times
I hope this helps!

blue83
Posts: 157
Joined: 11 Apr 2018, 06:38

Re: Whatsapp & Telegram Automation

Post by blue83 » 25 May 2020, 06:02

Hi @gregster ,

Thank you on all of this, I got it and understood everything.

But you know for what I need it?
To track my bots from various computers (not on same network) and besides that they let me know and send me to Telegram app I need storage for their data.

Here is problem that I can storage only my messages, but I need their messages to store in lets say .csv file.

I have tried with TCP-IP, but not working for computer on different networks.

Do you have an idea?

Thanks,
Blue

gregster
Posts: 8886
Joined: 30 Sep 2013, 06:48

Re: Whatsapp & Telegram Automation

Post by gregster » 25 May 2020, 10:27

blue83 wrote:
25 May 2020, 06:02
But you know for what I need it?
To track my bots from various computers (not on same network) and besides that they let me know and send me to Telegram app I need storage for their data.

Here is problem that I can storage only my messages, but I need their messages to store in lets say .csv file.
I am afraid I can't follow.

Who is "their" in "their messages"? You can store any messages that users send to your bots (if you also allow new users)...
And what is your setup of bots and computers? And what data needs to be stored and/or exchanged?

So far, I am not sure, if Telegram Bots will be suited for your needs...

blue83
Posts: 157
Joined: 11 Apr 2018, 06:38

Re: Whatsapp & Telegram Automation

Post by blue83 » 26 May 2020, 02:11

Hi @gregster ,

I am sorry for bad explanation.

I have robots on 30 computers and while working they are collecting data about their work.
I want that all that robots send data to one computer on differend network and that one robot save their data.

Data are number of times they do some stuff, saved time, processes etc.

I have found a way in Telegram desktop app how to extract data manually but if there is a way for automation of that task it will be great, I mean for reading that data in real time?

Thanks,
Blue

gregster
Posts: 8886
Joined: 30 Sep 2013, 06:48

Re: Whatsapp & Telegram Automation

Post by gregster » 26 May 2020, 13:19

blue83 wrote:
26 May 2020, 02:11
I have robots on 30 computers and while working they are collecting data about their work.
I want that all that robots send data to one computer on differend network and that one robot save their data.
Telegram bots are meant to interact with human users, not with other bots - they will ignore bot messages,afaik.
So it might be better to upload your data to a FTP server or dropbox or some cloud service from these computers... or perhaps via one of these socket methods you are investigating (sorry, I have no experience with these).

Of course, you could probably fake a human user by using browser automation and the Telegram webapp, but I am not sure if this would be very reliable.
I have found a way in Telegram desktop app how to extract data manually but if there is a way for automation of that task it will be great, I mean for reading that data in real time?
I haven't tried it with the desktop app (but I think that is what SL5 was referring to, in this same topic), but personally I would probably try to automate the browser-based webapp instead (via the Chrome.ahk or IE COM approach), if I would try this.

But I still doubt that this is the best way to exchange data between different computers.

blue83
Posts: 157
Joined: 11 Apr 2018, 06:38

Re: Whatsapp & Telegram Automation

Post by blue83 » 28 May 2020, 12:38

Hi @gregster ,

Thank you for this function.

Yes, some part are missing (reading bot messages directly, but desktop app can resolve that), but after all it can send messages from any computer with internet (not just local net), so this is for now my first choice.

Thank you

User avatar
Frosti
Posts: 426
Joined: 27 Oct 2017, 14:30
Contact:

Re: Whatsapp & Telegram Automation

Post by Frosti » 30 May 2020, 07:12

This is maybe the main Telegram thread in this forum. So I ask my question here.

I build a short script that check's clipboard changes. If it finds a URL in the cliboard, it asks me whether it should send it to my bot.
Okay the sending works. Unfortunately, the Telegram API interprets the URL attached as a text message in some form.
So I only get a part of the text message.

sending this: https://www.autohotkey.com/boards/viewtopic.php?f=6&t=62701
and I receive this: https://www.autohotkey.com/boards/viewtopic.php?f=6

The unholy sign & breaks it.
So far I have not dealt with HTTP and postings. I think this and probably other characters need to be converted.
Unfortunately, I didn't find an answer to my quick search.

User avatar
Frosti
Posts: 426
Joined: 27 Oct 2017, 14:30
Contact:

Re: Whatsapp & Telegram Automation

Post by Frosti » 30 May 2020, 11:24

I remembered reading something about UriEncode and exactly this solves my little misunderstanding.

Code: Select all

Telegram_Send(telegramBotKey, telegramChatId, textMessage) {				                                		;-- a way to send a text message

    WinHTTP := ComObjCreate("WinHTTP.WinHttpRequest.5.1")
    WinHTTP.Open("POST", Format("https://api.telegram.org/bot{1}/sendMessage?chat_id={2}&text={3}"
                                   , telegramBotKey, telegramChatId, uriEncode(textMessage)), 0)
    WinHTTP.Send()

Return WinHTTP.ResponseText
}

uriEncode(str) { ; v 0.3 / (w) 24.06.2008 by derRaphael / zLib-Style release
	b_Format := A_FormatInteger
	data := ""
	SetFormat,Integer,H
	Loop,Parse,str
		if ((Asc(A_LoopField)>0x7f) || (Asc(A_LoopField)<0x30) || (asc(A_LoopField)=0x3d))
			data .= "%" . ((StrLen(c:=SubStr(ASC(A_LoopField),3))<2) ? "0" . c : c)
		Else
			data .= A_LoopField
	SetFormat,Integer,%b_format%
	return data
}

gregster
Posts: 8886
Joined: 30 Sep 2013, 06:48

Re: Whatsapp & Telegram Automation

Post by gregster » 01 Jun 2020, 16:21

Frosti wrote:
30 May 2020, 07:12
sending this: https://www.autohotkey.com/boards/viewtopic.php?f=6&t=62701
and I receive this: https://www.autohotkey.com/boards/viewtopic.php?f=6

The unholy sign & breaks it.
So far I have not dealt with HTTP and postings. I think this and probably other characters need to be converted.
Hi Frosti, this works as well:

Code: Select all

botToken := ""					; add your Telegram bot token
chatID := 						; add the chat ID
msg := "https://www.autohotkey.com/boards/viewtopic.php?f=6&t=62701"
msgbox % Telegram_Send(botToken, chatID, msg)

Telegram_Send(telegramBotKey, telegramChatId, textMessage) {				                                		

    WinHTTP := ComObjCreate("WinHTTP.WinHttpRequest.5.1")
   	WinHTTP.Open("POST", "https://api.telegram.org/bot" telegramBotkey "/sendMessage") 
	WinHTTP.SetRequestHeader("Content-Type", "application/json")	
	
 	body := "{""text"":""" textMessage """, ""chat_id"" :" telegramChatId "}"
	WinHTTP.Send(body)

	Return WinHTTP.ResponseText
}
I just saw that you are working on a TelegramBot class :thumbup: .
(I actually use a rather rudimentary class myself for my Telegram bots and always planned to publish it, once completed - but it didn't come to that in the last 3 years :shh: )

Shanghei
Posts: 28
Joined: 04 Jan 2021, 22:42

Re: Telegram Automation

Post by Shanghei » 10 Jun 2021, 06:56

Hi, was wonderig if there was way to monitor a telegram chatroom im in for a certain keyword. and if the keyword matches, for example if someone says "hold" that it will trigger one of my scripts i usually run manually. thank you!

gregster
Posts: 8886
Joined: 30 Sep 2013, 06:48

Re: Telegram Automation

Post by gregster » 10 Jun 2021, 10:39

Shanghei wrote:
10 Jun 2021, 06:56
Hi, was wonderig if there was way to monitor a telegram chatroom im in for a certain keyword. and if the keyword matches, for example if someone says "hold" that it will trigger one of my scripts i usually run manually. thank you!
By using the official Telegram Bot API ? Afaik, only if your bot is one of the group admins...

rc76
Posts: 144
Joined: 07 Nov 2020, 01:45

Re: Telegram Automation

Post by rc76 » 15 Aug 2021, 10:15

gregster wrote:
03 Jan 2018, 00:14
Happy new year!
Here is a cobbled together and superficially tested script that demonstrates some possibilities in Telegram messenger like getting 'Updates' (messages from users), simple parsing and calling corresponding functions, sending messages and creating custom keyboards or custom 'inline' keyboards (to be handled differently). My original script is much longer and more complex by now, but still chaotic and very specific for my needs (for example, I use a more complex parsing algorithm because I also implemented commands with multiple parameters). But I think that this might be a good starting point for you, if you are not there already.

Some things that you might want to add by and by:
*) user/customer management (--> scheduling individual messages)
*) log files
*) better parsing
*) ability to send pictures
*) (better) error-handling
*) 'help' command or an 'assistant'

I can probably help you with most of these things - I am working on it anyway for my own use cases.
I added some commentary to the script below, but if you have further questions, don't hesitate to ask.

To use the script, you have to include Coco's JSON lib (https://autohotkey.com/boards/viewtopic.php?t=627) and add the personal token of your Telegram bot at the top of your script. Also, for testing purposes you will have to add your own chat ID, because I added a (very basic) check for known/registered users.
In general, you can get all the updates from your bot (from everyone who starts a chat with it) and decide if you will answer all users/chat IDs or just your registered users/customers. It is generally possible to send something like personalized (registration) links to your customers, afaik.
Hope that helps.

Code: Select all

#include json.ahk																		; Coco's JSON library, get it here:   https://autohotkey.com/boards/viewtopic.php?t=627

botToken  :=  "xxxxxxxxx:yyyyyyyyyyyyyyyyyyy"					; add your Telegram bot token
chatID := xyz000001																		; add your chat ID for testing porposes

oCustomers := {}																; Object of user ids of registered customers -> add your customers, you can send them a personal registration link
oCustomers[chatID] := "My Name"											; add your chat id (and name) to the customer object for testing purposes
offset := ""																			; Telegram message offset

cmds := {	"Command1" : "somefunction"										; bundle commands (case insensitive) and corresponding script functions to call 
				, 	"Command2" : "somefunction"
				,   "Command3" : "somefunction"
				, 	"Show inline buttons" : "inlinebuttons"
				, 	"Remove keyboard" : "RemoveKeyb"  }

; add custom keyboard for testing
keyb=																		; json formatted string
( 
	{"keyboard":[ ["Command1", "Command2"], ["Show inline buttons", "Remove Keyboard"] ], "resize_keyboard" : true } 
)																			
url := "https://api.telegram.org/bot" botToken "/sendMessage?text=Keyboard added&chat_id=" chatID "&reply_markup=" keyb
json_message := URLDownloadToVar(url)   
	; msgbox % json_message

; Check for new updates 
 SetTimer, UpdateTimer, 1000							; every 1000 ms = 1 second
return
;---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Esc::ExitApp													; hit Escape to stop the script
;----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

UpdateTimer:																									; checks constantly for user input in your bot
stack := {}																										; message stack			

updates := GetUpdates(botToken, (offset+1))											; get (new) updates from your bot as JSON string; keep track of old messages  
	;msgbox % updates
oUpdates := JSON.Load(updates)											; create an AHK object from the JSON string
If oUpdates.ok																			; check if json answer was "ok" : true
{
		
	loop % oUpdates.result.MaxIndex()		; determine number of new messages (updates) 
			stack.Push(oUpdates.result[A_index])		; add all updates (=messages) to stack
	For key, msg in stack
	{
		from_id := first_name := mtext := last_name := username := ""
		if (msg.callback_query.data!="")									; inline buttons have to be handled differently than normal messages and normal keyboards
		{	
			from_id := msg.callback_query.from.id
			mtext := msg.callback_query.data
		}	
		else 																					; get message text or message from normal keyboard
		{		
			from_id := msg.message.from.id									; which ID sent the message?
			mtext := msg.message.text
					;first_name := msg.message.from.first_name
					;last_name := msg.message.from.last_name
					;username ;=  msg.message.from.username
		}
		offset := msg.update_id													; keep track of processed messages
	
		if oCustomers.Haskey(from_id)				; check for known users...   optional
		{	
				if cmds.Haskey(mtext)														; is message a known command?
				{
					fun := cmds[mtext]									;look up which function to call for a specific command
					%fun%(botToken, msg, from_id, mtext)			; call function
				}
				else
				{
					text := "Sorry... I don't know this command."				  
					;    url encoding for messages :  %0A = newline (\n)   	%2b = plus sign (+)		%0D for carriage return \r        single Quote ' : %27			%20 = space
					SendText(botToken, text, from_id)
				}
		}
		else
				Traytip, No, Unknown user, 3		
	}  ; end 'for' 
}
return

;--------------------------------------------------------  functions for user commands ---------------------------------------------------------------------------------------------------------
somefunction(botToken, msg, from_id, mtext) 
{
		if (msg.callback_query.id!="")						;  After the user presses a callback button, Telegram clients will display a progress bar until you call answerCallbackQuery 
		{	
			cbQuery_id := msg.callback_query.id
			; Notification and alert are optional
			url := "https://api.telegram.org/bot" botToken "/answerCallbackQuery?text=Notification&callback_query_id=" cbQuery_id "&show_alert=true"
			json_message := URLDownloadToVar(url)  
				;msgbox % json_message
		}
		text := "You chose " mtext				  
		SendText(botToken, text, from_id)        ;  url encoding for messages :  %0A = newline (\n)   	%2b = plus sign (+)		%0D for carriage return \r        single Quote ' : %27			%20 = space
		return
}
;--------------------------------------------------------------------
; add inline buttons
inlinebuttons(botToken, msg,  from_id, mtext="") 
{
	keyb=																	; json string:
	( 
		{"inline_keyboard":[ [{"text": "Command One" , "callback_data" : "Command1"}, {"text" : "Some button (Cmd3)",  "callback_data" : "Command3"} ] ], "resize_keyboard" : true } 
	)
	url := "https://api.telegram.org/bot" botToken "/sendMessage?text=Keyboard added&chat_id=" from_id "&reply_markup=" keyb
	json_message := URLDownloadToVar(url)   ; find this function at the next code box below
	return json_message		
}
;---------------------------------------------------------------------
; Remove custom keyboard 
 RemoveKeyb(botToken, msg, from_id, mtext="") 
 {
	keyb=
	( 
		{"remove_keyboard" : true } 
	)
	url := "https://api.telegram.org/bot" botToken "/sendMessage?text=Keyboard removed&chat_id=" from_id "&reply_markup=" keyb
	json_message := URLDownloadToVar(url)  
		;msgbox % json_message
	return
}	
;------------------------------------------  Telegram functions  --------------------------------------------------------------------------------------------------------
GetUpdates(token, offset="", updlimit=100, timeout=0)     
{							
	If (updlimit>100)
		updlimit := 100
	; Offset = Identifier of the first update to be returned.
	url := "https://api.telegram.org/bot" token "/getupdates?offset=" offset "&limit=" updlimit "&timeout=" timeout
	updjson := URLDownloadToVar(url)					
	return updjson
}
;------------------------------------------------
SendText(token, text, from_id, replyMarkup="",  parseMode="" )
{
		url := "https://api.telegram.org/bot" token "/sendmessage?chat_id=" from_ID "&text=" text "&reply_markup=" replyMarkup "&parse_mode=" parseMode
		json_message := URLDownloadToVar(url)
		return json_message
}
;----------------------------------- additional functions ------------------------------------------------------------------------------------------------------------------
URLDownloadToVar(url,ByRef variable=""){						; function originally by Maestrith, I think
	try																						; keep script from breaking if API is down or not reacting
	{	
		hObject:=ComObjCreate("WinHttp.WinHttpRequest.5.1")
		hObject.Open("GET",url)
		hObject.Send()
		variable:=hObject.ResponseText
		return variable
	}
}
(Hit 'Escape' key to stop the script)
Dear gregster, Thank you for the amazing code examples! I am very excited to know whether you have any updates on your work. It will be truly amazing if you may share some of the examples like you mentioned (i.e. better parsing, log files, scheduling etc).

I am trying to make a Binance crypto trading bot with AHK, however there are really lacking of examples. Do you by any chance know where maybe best places to look into it?

Thank you again gregster!

gregster
Posts: 8886
Joined: 30 Sep 2013, 06:48

Re: Telegram Automation

Post by gregster » 15 Aug 2021, 23:46

rc76 wrote:
15 Aug 2021, 10:15
gregster wrote:
03 Jan 2018, 00:14
Some things that you might want to add by and by:
*) user/customer management (--> scheduling individual messages)
*) log files
*) better parsing
*) ability to send pictures
*) (better) error-handling
*) 'help' command or an 'assistant'
Dear gregster, Thank you for the amazing code examples! I am very excited to know whether you have any updates on your work. It will be truly amazing if you may share some of the examples like you mentioned (i.e. better parsing, log files, scheduling etc).

I am trying to make a Binance crypto trading bot with AHK, however there are really lacking of examples. Do you by any chance know where maybe best places to look into it?

Thank you again gregster!
Hi @rc76, welcome to the AHK forums!
I have to admit that I am still running the same simple Telegram bots for some years now - for their simple tasks, their code is actually quite convoluted, iirc. The scripts pull some (mostly API) data and upload it to 3 bots (privately used; two pals are the only other users). I have only touched them if some API or website changed, making some edits necessary. That said, one of the bots can upload images (here is some related code: https://www.autohotkey.com/boards/viewtopic.php?t=68417#p294332). I guess, a simple logging could be achieved by some strategically placed FileAppends, and my rudimentary scheduling is just done by using SetTimer :)

I have helped with some Binance API calls a few years back, but since I personally don't use that service, I don't know if these code samples are still up-to-date:
https://www.autohotkey.com/boards/viewtopic.php?f=76&t=49256 (about authenticating your (private) Binance API calls)
https://www.autohotkey.com/boards/viewtopic.php?t=44370#p201080 (sorry, this post is in German - but this is only about basic (public) API calls which don't need API keys, iirc)

If you have some questions about these code snippets, feel free to ask. I'll try to help. I just haven't done much more with Telegram and Binance than what can be found on these forums. :shh: :shifty: (Well, I don't remember exactly. I think I have some more Telegram code somewhere - but it never made it into my actually used scripts. But one day... ;) )

rc76
Posts: 144
Joined: 07 Nov 2020, 01:45

Re: Telegram Automation

Post by rc76 » 16 Aug 2021, 21:18

Dear @gregster, thank you so so much for your kind help and guidance.

I will give the Binance code a try snippet by snippet and keep you posted on my progress.

The Telegram program is just amazing. Combining Telegram with AHK, you can really do so so much, not just perform the core business application, but also monitor and manage the Windows/Computer that the application runs on.

Thank you so much once again grester!

rc76
Posts: 144
Joined: 07 Nov 2020, 01:45

Re: Telegram Automation

Post by rc76 » 14 Sep 2021, 20:50

I noticed there is this new menu feature available in Telegram:
01.png
01.png (180.42 KiB) Viewed 2869 times
02.png
02.png (199.85 KiB) Viewed 2869 times
https://telegram.org/blog/animated-backgrounds#bot-menu

But I cannot find any API documentation on how the API syntax should be to call this new menu up.

This will be a great way to define the root "commands" for the chat bot.

Any chance @gregster have tried this?

gregster
Posts: 8886
Joined: 30 Sep 2013, 06:48

Re: Telegram Automation

Post by gregster » 16 Sep 2021, 11:13

rc76 wrote:
14 Sep 2021, 20:50
But I cannot find any API documentation on how the API syntax should be to call this new menu up.

This will be a great way to define the root "commands" for the chat bot.

Any chance @gregster have tried this?
To clarify, afaik, this is only supported (although automatically) for bot commands that start with a /, not for other commands to your bot (use a custom keyboard instead). This means, it just shows the same command flyout window that you would get, if you typed a / on a bot that offers such commands (like most third-party bots do). That still wouldn't be bad.

But it seems that this nice button is only fully supported on smart phones. The desktop app and the different browser apps only support it to a lesser extent, or not at all.
You can check, for example, with the Botfather bot, or set some commands yourself on your own bot (this is now also possible programmatically - for code, see below).

Screenshot from my android phone:
cell phone android.jpg
cell phone android.jpg (4.87 KiB) Viewed 2819 times


Browser z-app (https://web.telegram.org/z/). It shows a smaller 'burger' button.
The picture also shows part of the 'flyout' window with /-commands, in this case created by my code below:
browser z edition.jpg
browser z edition.jpg (7.24 KiB) Viewed 2819 times


Browser k-app (https://web.telegram.org/k/) - shows nothing at all (until you type /)
browser k edition.png
browser k edition.png (3.96 KiB) Viewed 2819 times


The desktop app just shows a / button on the right, that would type a / for you (and then the flyout would be shown):
desktop app.jpg
desktop app.jpg (5.15 KiB) Viewed 2819 times

Code example for adding, showing and deleting commands programmatically:

Code: Select all

; add your botToken

; set my commands - response should say 'ok'
arr = [{"command":"/fish","description": "get a fish"}, {"command":"/bird","description":"get a bird"}, {"command":"/dog","description":"get a dog"}] 			
param := "commands=" arr	
str := "https://api.telegram.org/bot" botToken "/setMyCommands?" 
msgbox % url_tovar(str, param)

; show my commands (optional)
param := ""
str := "https://api.telegram.org/bot" botToken "/getMyCommands" 
msgbox % url_tovar(str, param)

/*
; delete my commands
param := ""
str := "https://api.telegram.org/bot" botToken "/deleteMyCommands" 
msgbox % url_tovar(str, param)
*/

url_tovar(URL, param) {
	WebRequest := ComObjCreate("WinHttp.WinHttpRequest.5.1")
	WebRequest.Open("POST", URL)
	WebRequest.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded")
	WebRequest.Send(param)
	res := WebRequest.ResponseText
	return res
}

rc76
Posts: 144
Joined: 07 Nov 2020, 01:45

Re: Telegram Automation

Post by rc76 » 16 Sep 2021, 16:03

It works like a dream @gregster.

This nice little bottom will work well as root commands (where you can some some hint about the command as well). Root commands such as:

/start
/status
/clear

For /clear, it be ideal if we can sort of clear up the chat screen (i.e. make it scroll such that you do not see any historical message?). Any chance you may have tried something like it? Or maybe its a redundant feature, should just return to /start.

Currently all I can do is to make it clear out the keyboard

Code: Select all

keyboard_remove =
(
  {"remove_keyboard" : true }
)
url := "https://api.telegram.org/bot" my_token "/sendMessage?text=AHK: Screen Cleared&chat_id=" my_chatID "&reply_markup=" keyboard_remove
json_message := URLDownloadToVar(url)

rc76
Posts: 144
Joined: 07 Nov 2020, 01:45

Re: Telegram Automation

Post by rc76 » 16 Sep 2021, 16:08

Also I have been running @gregster's amazing Telegram loop, to capture any updates from the bot.

However I did experience lag on the bot running on Windows, not sure whether it is because the loop script is taking alot of load.

I did some search and found the following optimization code that can be added on the script. I think it sort of helped to reduce some lag on the script. But honestly I can't find all the explanation about each of the optimization code. Here is what I have:

Code: Select all

; Script Optimization

; #Warn           ; Enable warnings to assist with detecting common errors.

#NoEnv          ; Recommended for performance and compatibility with future AHK releases.
SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.
#Persistent

#maxhotkeysperinterval 99000000
#hotkeyinterval 99000000
#keyhistory 0
listlines off
setbatchlines -1
setwindelay -1
Any thoughts/feedback/improvement on the optimization?

Once again, none of the above is possible without @gregster's example. Thank you gregster once again!

Post Reply

Return to “Ask for Help (v1)”