Advertisement
Manusman

Telegram Game Bot

Jul 18th, 2021 (edited)
1,735
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.68 KB | None | 0 0
  1. import pyautogui
  2. import telegram.error
  3. from win32 import win32gui
  4. from telegram.ext import Updater, CommandHandler, CallbackContext, Dispatcher, ConversationHandler, MessageHandler, \
  5.                          Filters
  6. from telegram import Update, InputMediaPhoto
  7. import subprocess
  8. import io
  9. from typing import Optional
  10. import threading
  11. import time
  12. from PIL import Image
  13. from pynput.keyboard import Controller
  14.  
  15. TOKEN = 'XXXXXXXXXXXXXXXXXXXXXXXX'
  16. SNAKE_PATH = r"C:\Users\...\Snake\script.py"
  17. snake_process: Optional[subprocess.Popen] = None
  18.  
  19.  
  20. def screenshot(window_title: Optional[str] = None) -> Image:
  21.     """Get a screenshot of the window with window_title"""
  22.     if window_title:
  23.         hwnd = win32gui.FindWindow(None, window_title)
  24.         if hwnd:
  25.             try:
  26.                 win32gui.SetForegroundWindow(hwnd)
  27.             except Exception:
  28.                 pass
  29.             x, y, x1, y1 = win32gui.GetClientRect(hwnd)
  30.             x, y = win32gui.ClientToScreen(hwnd, (x, y))
  31.             x1, y1 = win32gui.ClientToScreen(hwnd, (x1 - x, y1 - y))
  32.             image = pyautogui.screenshot(region=(x, y, x1, y1))
  33.             return image
  34.     else:
  35.         image = pyautogui.screenshot()
  36.         return image
  37.  
  38.  
  39. def send_snake_images(update: Update, context: CallbackContext, process: subprocess.Popen) -> None:
  40.     """Threaded function that sends and continuously edits a photo with screenshots"""
  41.     first = True
  42.     msg = None
  43.     while process.poll() is None:
  44.         if image := screenshot('Snake'):  # Gets a screenshot of the window
  45.             bytesio = io.BytesIO()
  46.             image.save(bytesio, format='PNG')
  47.             bytes_image = bytes(bytesio.getvalue())     # Convert to bytes object
  48.             if first:       # First time send a full message
  49.                 msg = context.bot.send_photo(update.message.chat_id, bytes_image)
  50.                 first = False
  51.  
  52.             else:
  53.                 try:
  54.                     msg.edit_media(media=InputMediaPhoto(media=bytes_image))  # Edit the message with the next photo
  55.                 except telegram.error.BadRequest:
  56.                     pass
  57.  
  58.  
  59. def snake(update: Update, context: CallbackContext) -> str:
  60.     """Callback for /snake command- starts the game and screenshot sending"""
  61.     global snake_process
  62.     snake_process = subprocess.Popen(['python', SNAKE_PATH])
  63.     time.sleep(2)           # Wait for the window to open
  64.     thread = threading.Thread(target=send_snake_images, args=(update, context, snake_process))
  65.     thread.start()              # Start thread that wil send photos
  66.     return "StartReceivingDirections"       # Move to next state
  67.  
  68.  
  69. def exit_snake(update: Update, context: CallbackContext) -> int:
  70.     """Exit callback"""
  71.     if snake_process is not None and snake_process.poll() is None:
  72.         snake_process.terminate()       # End the game process
  73.     return -1       # End the conversation
  74.  
  75.  
  76. def get_directions(update: Update, context: CallbackContext) -> None:
  77.     """Callback to text - will press the button"""
  78.     keyboard = Controller()
  79.     keyboard.press(update.message.text[0])      # press the first letter
  80.     keyboard.release(update.message.text[0])
  81.  
  82.  
  83. def main():
  84.     updater: Updater = Updater(TOKEN)
  85.  
  86.     entry_points = [CommandHandler('snake', snake)]     # Snake game conversation
  87.     states = {"StartReceivingDirections": [CommandHandler('exit', exit_snake),
  88.                                            MessageHandler(Filters.text & (~Filters.command), get_directions)]}
  89.     fallbacks = []
  90.     updater.dispatcher.add_handler(ConversationHandler(entry_points, states, fallbacks))
  91.  
  92.     updater.start_polling()
  93.     updater.idle()
  94.  
  95.  
  96. if __name__ == '__main__':
  97.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement