오토핫키(Autohotkey) 텔레그램 연동하기 본문

프로그래밍/AutoHotkey

오토핫키(Autohotkey) 텔레그램 연동하기


이 설명을 진행하기에 앞서 텔레그램 봇을 이미 만든 상태에서 진행해주시기 바랍니다.


텔레그램 봇 만들기는 검색을 통해서 알아서 찾아 해주시면 되겠습니다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
; #Warn  ; Enable warnings to assist with detecting common errors.
SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.
 
RandomVariable = sting with variable: %A_OSType%
 
Telegram_MsgBox(16,1,"string")                         ;icon before text
Telegram_MsgBox(32,2,RandomVariable)                 ;icon after text
Telegram_MsgBox("%F0%9F%8E%88",2,RandomVariable)     ;own icon
Telegram_MsgBox(0,a,"string with space")            ;no icon    
 
Telegram_MsgBox(Option,EmojiPosition,Text)
{
    TelegramBotToken = 
    TelegramBotChatID = 
    
    if TelegramBotChatID =
        Telegram_FirstCFG()
    if TelegramBotChatID =
        Telegram_FirstCFG()
    
    if Option=16
        TelegramIconString := "%E2%9D%8C"
    if Option=32
        TelegramIconString := "%E2%9D%94"
    if Option=48
        TelegramIconString := "%E2%9A%A0%EF%B8%8F"
    if Option=64
        TelegramIconString := "%E2%84%B9%EF%B8%8F"
    
    IfInString, Option, `%
        TelegramIconString := Option
 
    IfLessOrEqual, EmojiPosition, 1
        Text = %TelegramIconString% %Text%
    
    IfGreaterOrEqual, EmojiPosition, 2
        Text = %Text% %TelegramIconString%
        
    loop 3
    {
        UrlDownloadToFile https://api.telegram.org/bot%TelegramBotToken%/sendmessage?chat_id=%TelegramBotChatID%&text=%Text%, %A_ScriptDir%\check.rups
        sleep 1000
        ifexist %A_ScriptDir%\check.rups
        {
            break
        }
        if A_index = 3
        {
            MsgBox, 16,, something went wrong with sending
        }
    }
    filedelete %A_ScriptDir%\check.rups
}
 
Telegram_FirstCFG()
{
    msgbox open telegram and open a new Chat with @botfater`nif yout dont know how you do that, search in your default serach engine for "Telegram Botfather first bot"`n`nyou need to choose a unique name (you cant change it)
    loop
    {
        InputBox, BotToken, enter the in telegram indicated bot token, 
        MsgBox, 4, , Bot Token correct?:`n%BotToken%
            IfMsgBox Yes
                break
    }
    
    Random, SecurityCode, 10009999
    msgbox now open a new chat with your new created bot (search for @*yourbotname* and start a new chat) and enter this number %SecurityCode% and send it via telegram`n press OK, when done.
    UrlDownloadToFile https://api.telegram.org/bot%BotToken%/getupdates , %A_ScriptDir%\findChatID.txt
    sleep 2000
    run %A_ScriptDir%\findChatID.txt
    msgbox now search for the number %SecurityCode% and on the same line there should be something like: "chat":{"id":782163891`n`nfound it? press ok
    InputBox ChatID, enter the number after "chat":{"id": here:
    FileAppend, Telegram Bot Token = %BotToken%`n, %A_ScriptDir%\TokenAndID.txt
    FileAppend, Telegram Chat ID = %ChatID%, %A_ScriptDir%\TokenAndID.txt
    run %A_ScriptDir%\TokenAndID.txt
    msgbox here you go. copy and past the values to the variables TelegramBotToken & TelegramChatID in the sourcecode.`n`n(you can delte all the .txt files)
    exitapp
}
 
 
cs

출처 : https://autohotkey.com/boards/viewtopic.php?t=24919



텔레그램 봇파더를 통해 봇을 생성하신 분은 텔레그램 봇의 토큰을 받으셨을겁니다.


해당 스크립트를 실행 시키신 후 자신의 봇 토큰을 입력해주세요.


그 다음에 메세지에 뜨는 4자리 숫자를 자신의 봇에게 대화 시작하기 후, 입력해줍니다.


입력해주었다면 버튼을 눌러 넘어가주세요.


그럼 스크립트를 실행한 폴더에 TokenAndID.txt라는 파일이 생겼을 겁니다.


거기에서 Telegram Bot Token 이 자신의 봇 토큰, Telegram Chat ID가 자신의 텔레그램 아이디 고유번호입니다.




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
url = "{}" ; 반드시 여기에 주소를 입력해주세요!
ckid = "";자신의 텔레그램 아이디 고유번호를 입력해주세요
; 입력을 안 할 경우 모든 사용자 입력에 대해 프로그램이 실행됩니다.
ReadURL(URL, encoding = "utf-8") {
    static a := "AutoHotkey/" A_AhkVersion
    
    if (!DllCall("LoadLibrary""str""wininet"|| !(h := DllCall("wininet\InternetOpen""str", a, "uint"1"ptr"0"ptr"0"uint"0"ptr")))
        return 0
    
    c := s := 0, o := ""
    
    if (f := DllCall("wininet\InternetOpenUrl""ptr", h, "str", url, "ptr"0"uint"0"uint"0x80003000"ptr"0"ptr"))
    {
        while (DllCall("wininet\InternetQueryDataAvailable""ptr", f, "uint*", s, "uint"0"ptr"0&& s > 0)
        {
            VarSetCapacity(b, s, 0)
            DllCall("wininet\InternetReadFile""ptr", f, "ptr"&b, "uint", s, "uint*", r)
            o .= StrGet(&b, r >> (encoding = "utf-16" || encoding = "cp1200"), encoding)
        }
        DllCall("wininet\InternetCloseHandle""ptr", f)
    }
    DllCall("wininet\InternetCloseHandle""ptr", h)
    return o
}
 
cs

위 코드는 URL에 접속하여 해당 URL에 Request값을 받아오는 코드입니다.

URL은 앞에서 언급했듯이  https://api.telegram.org/bot[Telegram Bot Token]/getupdates 입니다. 

(Telegram Bot Token에 자신의 토큰을 집어넣으세요)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
    GetMsg := ReadURL(url)
    
    Pos = 0
    Pos := RegExMatch(GetMsg, "`n)(.*)", Output, Pos+1+ StrLen(Output)
 
 
    Pos := RegExMatch(GetMsg, "`n)(.*)", Output, Pos+1+ StrLen(Output)
 
    RegExMatch(Output, """chat"":{""id"":(.*),""first", id)
 
    RegExMatch(Output, """date"":(.*),""text"date)
 
    RegExMatch(Output, """text"":""(.*)"",""entities", texta)

if(id != ckid)
{
return ;자신 이외에 사람이 입력한 경우 아무것도 반환안해줍니다.
}
 
 

cs



위 드는 Request 값에서 정규식을 이용해 Command 분류(/start 와 같이 앞에 슬래쉬 뒤 문자)의 문자들을 긁어옵니다.

매번 같은 명령을 긁어올 수 없으므로 시간값을 따로 txt파일로 계속 저장하면서 시간값 이후의 명령만 읽어오도록합니다.

1
2
3
4
5
6
7
8
    IniRead,rdate,Community.ini,RecentMsg,Date
 
    if (rdate < date1 and date1 <> "" and texta1 <> "")
    {
        if trim(texta1) = "/start"
                Msgbox, Hi
    }
 
cs
 



texta1 은 이제 텔레그램 봇에게 입력되는 모든 글자에 대한 값입니다.

/start를 입력했다면 메세지 박스로 hi라는 글자가 떠오르게 되겟죠?