텔레그램 봇 코딩하실 줄 아시는 분 계신가요 ㅠㅠ

Elsaphaba   
   조회 6388   추천 0    

 

안녕하세요....

현재 스마트 플러그를 이용해 WOL과 비슷한 기능을 구축했습니다!

하지만 서버를 끄려면 RDP를 켜서 직접 종료 버튼을 눌러야 하는 불편함이 있어서

더욱 효과적으로 관리하기 위해 '텔레그램에 서버의 CMD를 연계시키는 봇'을 만들기로 결심하였습니다!

프로그래밍은 막 C언어를 배운 참이라 구글링해서 여러 코드들을 짜집기해 만들었습니다.


하지만... 열심히 구글링으로 짜집기하고 디버깅을 했음에도 불구하고 작동이 되지 않습니다 ㅠㅠ

디버깅은 모두 해 에러 메세지는 뜨지 않습니다만..... .py 파일을 실행하면 켜졌다 바로 꺼집니다

구글링을 해봐도 대부분 CDN에서 운영하는 내용밖에 안나와 대처 방법을 잘 모르겠습니다


혹시 텔레그램 봇을 코딩하실 줄 아시는 분이 계시다면 무엇이 문제인지 알 수 있을까요?

혹시 윈도우에서 구동할 경우 따로 설치해야하는 프로그램이 있는건가요?


구동 환경은 Windows Server 2019이고 실행파일은 .py 파일입니다.

Python-Telegram-Bot 패키지를 설치한 상태입니다.

https://github.com/python-telegram-bot/python-telegram-bot

#기본패키지
import time
#텔레그램 봇 패키지
from telegram.ext import Updater, MessageHandler, Filters, CommandHandler
from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove, InlineKeyboardButton, InlineKeyboardMarkup
#CMD 패키지
import os
import subprocess


BOT_TOKEN='(토큰 입력)'
updater = Updater( token=BOT_TOKEN, use_context=True )
dispatcher = updater.dispatcher 


#시작
def start(update, context): 
    bot.send_message(chat_id=update.effective_chat.id, text="Enter Password")


    #사용자 확인 및 분기
    def get_message(bot, update) :
       message = update.message.text    
       if message == "Password Key" :


            #Keyword 삭제
             bot.deleteMessage(chat_id=update.message.chat_id, message_id=forward_from_message_id)


            #바로명령 키보드
             KBMenu = [[telegram.KeyboardButton('shutdown')],
                           [telegram.KeyboardButton('Ipconfig /all')]]
             KBMenu_markup = telegram.ReplyKeyboardMarkup(KBMenu)
             bot.send_message(chat_id=update.message.chat_id,
                     text="Direct Order Keyboard",
                     reply_markup=KBMenu_markup)




            #CMD 실행
            def get_message(bot, update) :
            Order = update.message.text


             cmd = Order
             Result = subprocess.getstatusoutput(cmd)
             bot.send_message(chat_id=update.message.chat_id, text=Result)
        
             updater.start_polling() 
             updater.idle()
       
        else :
            bot.stop()
짧은글 일수록 신중하게.
작은꼬마 2020-09
트위터  특정 계정을 모니터링하다가 Shutdown 명령어 내리면 알아서 꺼지는게 있던데......
http://rabbit129.cafe24.com/gooday//bbs/board.php?bo_table=scrap&wr_id=149

지금 쓰시는 시스템에 호환되는지 모르겠습니다.

공개로 글쓰기 하면되는지라 컨트롤은 무지 쉬운데 말이죠....


IFTTT에 트위터 웹훅이 있으니 폰 시리나 구글어시스턴트 연동해서 트위트에 글쓰게 만들어주시면 편하게 쓰실수있지 않을까 싶어요. (더 하실수있으면 ioT 디바이스에 스위치 누르는걸로.. 글쓰게..라던가..)
김제연 2020-09
와.. node 만 보다가 .. 파이썬 코드 보니까 .. 순차적이라 바로 이해가 되네요 ㅜㅜ
파이썬 할껄 잘못했네요 ㅋ
김제연 2020-09
스타트를 안해주신거 같은데요
__init__ 메인 함수에 .. start 함수 불려와야 하는거 아닌가요?

__init__ 없어도 .. start(updater,context) 해주면 실행 되지 않나요?
context 는 뭔가요? 시작 함수에..
그리고
함수를 저렇게 중첩해서 써도 되나요?
함수 밖으로 빼야 하는거 아닌가요?
start() 함수를 실행하고 그 안에서 다시  get_message 해야 하는거 아닌가요?
병따개님 2020-09
파이썬은 잘 몰라서 다른 방법을 제시해보자면
openssh 서버를 설치해서 ssh로 shoudown 명령어를 보내면 될거같아요
김제연 2020-09
https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/echobot.py
여기 참조 하셔서 .. 새로 만드셔야 할것 같습니다.

위의 예제에
dp.add_handler(CommandHandler("help", help_command)) 아래쪽에
dp.add_handler(CommandHandler("shutdown", shutdown_command))

넣으시고
def help_command(update, context):
    """Send a message when the command /help is issued."""
    update.message.reply_text('Help!')

아래쪽에
def shutdown_command(update, context):
    """Send a message when the command /help is issued."""
            Result = subprocess.getstatusoutput('shutdown')
            bot.send_message(chat_id=update.message.chat_id, text=Result)
    update.message.reply_text('Help!')


이런식으로요 ..
버튼 나오게 하는것도 .. 차이 없을껍니다 버튼 눌러지면 message로 받아서 넘겨주고요..
김제연 2020-09
그리고 해보니
import os
import subprocess

result = subprocess.getstatusoutput('ipconfig /all')
print(result[1])

2번째 배열값으로 stdout 가 넘어오네요 .. result 를 텔레그램으로 넘겨주면.. 이상하게 넘어갈듯 하네요 .
넘기실때 Result[1] 을 보내주셔야 할듯
RIGIDBODY 2020-09
그냥, IFTTT 하고 Webhook과 Google assistant 와 Joins에 Eventghost연동하면 핸폰에서 음성명령이나 타이핑으로 종료시킬 수 있습니다.


QnA
제목Page 5717/5718
2014-05   5213403   정은준1
2015-12   1744361   백메가
2017-02   4380   지니보이
2019-06   3018   2cpumem
2023-09   2562   가빠로구나
2017-02   6181   무슨생각
2019-06   2887   안규민
2020-09   3485   로벨리아
2010-08   8715   정은준1
2013-07   6540   김재학23
2014-12   15538  
2010-08   8717   이종송1
2013-08   13981   박정길infoeyes
2020-09   6389   Elsaphaba
2023-10   3870   두마스터
2017-02   4132   Astarot
2018-05   4254   김경환M
2013-08   6574   병맛폰
2015-01   8700   AKA지니
2013-08   12312   user
2015-01   9117   지수삼촌
2013-08   9768   야만고양이