Skip to content

Commit

Permalink
Initial commit. Webhooks and standalone-mode support. Commands /start…
Browse files Browse the repository at this point in the history
… and /roll
  • Loading branch information
satanas committed Aug 19, 2019
0 parents commit a6b4e2c
Show file tree
Hide file tree
Showing 9 changed files with 737 additions and 0 deletions.
25 changes: 25 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
node_modules/*

# Serverless directories
.serverless
serverless.env.yml

# Others
*.pyc
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
AWS credentials saved on your machine at ~/.aws/credentials.
38 changes: 38 additions & 0 deletions handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import os
import json
import logging
import telegram


logger = logging.getLogger()
if logger.handlers:
for handler in logger.handlers:
logger.removeHandler(handler)
logging.basicConfig(level=logging.INFO)

def hello(event, context):
logger.info('Event: {}'.format(event))
body = {
"message": "Go Serverless v1.0! Your function executed successfully!",
"input": event
}

response = {
"statusCode": 200,
"body": json.dumps(body)
}

return response

# Use this code if you don't use the http event with the LAMBDA-PROXY
# integration
"""
return {
"message": "Go Serverless v1.0! Your function executed successfully!",
"event": event
}
"""

if __name__ == "__main__":
print("mmgv")
hello("asdasdasdasd", None)
102 changes: 102 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import os
import json
import logging

import telegram
from roll import handler as roll_handler
from telegram.ext import Updater
from telegram.ext import CommandHandler

logger = logging.getLogger()
if logger.handlers:
for handler in logger.handlers:
logger.removeHandler(handler)
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)

OK_RESPONSE = {
'statusCode': 200,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps('ok')
}
ERROR_RESPONSE = {
'statusCode': 400,
'body': json.dumps('Oops, something went wrong!')
}

TELEGRAM_TOKEN = os.environ.get('TELEGRAM_TOKEN')
if not TELEGRAM_TOKEN:
logger.error('The TELEGRAM_TOKEN must be set')
raise NotImplementedError

updater = Updater(token=TELEGRAM_TOKEN)
dispatcher = updater.dispatcher

def start(bot, update, **args):
bot.send_message(chat_id=update.message.chat_id, text="Welcome to Dungeons and Dragons on Telegram.")

start_cmd = CommandHandler('start', start)
roll_cmd = CommandHandler('roll', roll_handler)

dispatcher.add_handler(start_cmd)
dispatcher.add_handler(roll_cmd)



def configure_telegram():
"""
Configures the bot with a Telegram Token.
Returns a bot instance.
"""

TELEGRAM_TOKEN = os.environ.get('TELEGRAM_TOKEN')
if not TELEGRAM_TOKEN:
logger.error('The TELEGRAM_TOKEN must be set')
raise NotImplementedError

return telegram.Bot(TELEGRAM_TOKEN)


def webhook(event, context):
"""
Runs the Telegram webhook.
"""

bot = configure_telegram()
logger.info('Event: {}'.format(event))

if event.get('httpMethod') == 'POST' and event.get('body'):
update = telegram.Update.de_json(json.loads(event.get('body')), bot)
chat_id = update.message.chat.id
text = update.message.text

if text.startswith('/start'):
start(bot, update)
elif text.startswith('/roll'):
roll_handler(bot, update)

return OK_RESPONSE

return ERROR_RESPONSE


def set_webhook(event, context):
"""
Sets the Telegram bot webhook.
"""

logger.info('Event: {}'.format(event))
bot = configure_telegram()
url = 'https://{}/{}/'.format(
event.get('headers').get('Host'),
event.get('requestContext').get('stage'),
)
webhook = bot.set_webhook(url)

if webhook:
return OK_RESPONSE

return ERROR_RESPONSE

if __name__ == "__main__":
updater.start_polling()
Loading

0 comments on commit a6b4e2c

Please sign in to comment.