Move imports in telegram_bot component ()

pull/49490/head
Quentame 2019-10-18 02:19:34 +02:00 committed by Paulus Schoutsen
parent 2d1f7932ba
commit bd0403c65e
3 changed files with 18 additions and 16 deletions
homeassistant/components/telegram_bot

View File

@ -7,6 +7,16 @@ import logging
import requests import requests
from requests.auth import HTTPBasicAuth, HTTPDigestAuth from requests.auth import HTTPBasicAuth, HTTPDigestAuth
from telegram import (
Bot,
InlineKeyboardButton,
InlineKeyboardMarkup,
ReplyKeyboardMarkup,
ReplyKeyboardRemove,
)
from telegram.error import TelegramError
from telegram.parsemode import ParseMode
from telegram.utils.request import Request
import voluptuous as vol import voluptuous as vol
from homeassistant.components.notify import ATTR_DATA, ATTR_MESSAGE, ATTR_TITLE from homeassistant.components.notify import ATTR_DATA, ATTR_MESSAGE, ATTR_TITLE
@ -375,8 +385,6 @@ async def async_setup(hass, config):
def initialize_bot(p_config): def initialize_bot(p_config):
"""Initialize telegram bot with proxy support.""" """Initialize telegram bot with proxy support."""
from telegram import Bot
from telegram.utils.request import Request
api_key = p_config.get(CONF_API_KEY) api_key = p_config.get(CONF_API_KEY)
proxy_url = p_config.get(CONF_PROXY_URL) proxy_url = p_config.get(CONF_PROXY_URL)
@ -396,7 +404,6 @@ class TelegramNotificationService:
def __init__(self, hass, bot, allowed_chat_ids, parser): def __init__(self, hass, bot, allowed_chat_ids, parser):
"""Initialize the service.""" """Initialize the service."""
from telegram.parsemode import ParseMode
self.allowed_chat_ids = allowed_chat_ids self.allowed_chat_ids = allowed_chat_ids
self._default_user = self.allowed_chat_ids[0] self._default_user = self.allowed_chat_ids[0]
@ -457,7 +464,6 @@ class TelegramNotificationService:
- a string like: `/cmd1, /cmd2, /cmd3` - a string like: `/cmd1, /cmd2, /cmd3`
- or a string like: `text_b1:/cmd1, text_b2:/cmd2` - or a string like: `text_b1:/cmd1, text_b2:/cmd2`
""" """
from telegram import InlineKeyboardButton
buttons = [] buttons = []
if isinstance(row_keyboard, str): if isinstance(row_keyboard, str):
@ -507,8 +513,6 @@ class TelegramNotificationService:
params[ATTR_REPLY_TO_MSGID] = data[ATTR_REPLY_TO_MSGID] params[ATTR_REPLY_TO_MSGID] = data[ATTR_REPLY_TO_MSGID]
# Keyboards: # Keyboards:
if ATTR_KEYBOARD in data: if ATTR_KEYBOARD in data:
from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove
keys = data.get(ATTR_KEYBOARD) keys = data.get(ATTR_KEYBOARD)
keys = keys if isinstance(keys, list) else [keys] keys = keys if isinstance(keys, list) else [keys]
if keys: if keys:
@ -517,9 +521,8 @@ class TelegramNotificationService:
) )
else: else:
params[ATTR_REPLYMARKUP] = ReplyKeyboardRemove(True) params[ATTR_REPLYMARKUP] = ReplyKeyboardRemove(True)
elif ATTR_KEYBOARD_INLINE in data:
from telegram import InlineKeyboardMarkup
elif ATTR_KEYBOARD_INLINE in data:
keys = data.get(ATTR_KEYBOARD_INLINE) keys = data.get(ATTR_KEYBOARD_INLINE)
keys = keys if isinstance(keys, list) else [keys] keys = keys if isinstance(keys, list) else [keys]
params[ATTR_REPLYMARKUP] = InlineKeyboardMarkup( params[ATTR_REPLYMARKUP] = InlineKeyboardMarkup(
@ -529,7 +532,6 @@ class TelegramNotificationService:
def _send_msg(self, func_send, msg_error, *args_msg, **kwargs_msg): def _send_msg(self, func_send, msg_error, *args_msg, **kwargs_msg):
"""Send one message.""" """Send one message."""
from telegram.error import TelegramError
try: try:
out = func_send(*args_msg, **kwargs_msg) out = func_send(*args_msg, **kwargs_msg)

View File

@ -1,6 +1,10 @@
"""Support for Telegram bot using polling.""" """Support for Telegram bot using polling."""
import logging import logging
from telegram import Update
from telegram.error import TelegramError, TimedOut, NetworkError, RetryAfter
from telegram.ext import Updater, Handler
from homeassistant.const import EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP from homeassistant.const import EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP
from homeassistant.core import callback from homeassistant.core import callback
@ -32,8 +36,6 @@ async def async_setup_platform(hass, config):
def process_error(bot, update, error): def process_error(bot, update, error):
"""Telegram bot error handler.""" """Telegram bot error handler."""
from telegram.error import TelegramError, TimedOut, NetworkError, RetryAfter
try: try:
raise error raise error
except (TimedOut, NetworkError, RetryAfter): except (TimedOut, NetworkError, RetryAfter):
@ -45,8 +47,6 @@ def process_error(bot, update, error):
def message_handler(handler): def message_handler(handler):
"""Create messages handler.""" """Create messages handler."""
from telegram import Update
from telegram.ext import Handler
class MessageHandler(Handler): class MessageHandler(Handler):
"""Telegram bot message handler.""" """Telegram bot message handler."""
@ -72,7 +72,6 @@ class TelegramPoll(BaseTelegramBotEntity):
def __init__(self, bot, hass, allowed_chat_ids): def __init__(self, bot, hass, allowed_chat_ids):
"""Initialize the polling instance.""" """Initialize the polling instance."""
from telegram.ext import Updater
BaseTelegramBotEntity.__init__(self, hass, allowed_chat_ids) BaseTelegramBotEntity.__init__(self, hass, allowed_chat_ids)

View File

@ -2,6 +2,8 @@
import datetime as dt import datetime as dt
import logging import logging
from telegram.error import TimedOut
from homeassistant.components.http import HomeAssistantView from homeassistant.components.http import HomeAssistantView
from homeassistant.components.http.const import KEY_REAL_IP from homeassistant.components.http.const import KEY_REAL_IP
from homeassistant.const import ( from homeassistant.const import (
@ -26,7 +28,6 @@ REMOVE_HANDLER_URL = ""
async def async_setup_platform(hass, config): async def async_setup_platform(hass, config):
"""Set up the Telegram webhooks platform.""" """Set up the Telegram webhooks platform."""
import telegram
bot = initialize_bot(config) bot = initialize_bot(config)
@ -55,7 +56,7 @@ async def async_setup_platform(hass, config):
while retry_num < 3: while retry_num < 3:
try: try:
return bot.setWebhook(handler_url, timeout=5) return bot.setWebhook(handler_url, timeout=5)
except telegram.error.TimedOut: except TimedOut:
retry_num += 1 retry_num += 1
_LOGGER.warning("Timeout trying to set webhook (retry #%d)", retry_num) _LOGGER.warning("Timeout trying to set webhook (retry #%d)", retry_num)