Getting the status of a stream
def checkstream():
global streamer_name
streamer_name = 'streamer_name'
body = {
'client_id': 'ID',
'client_secret': 'SECRET',
"grant_type": 'client_credentials'
}
r = requests.post('https://id.twitch.tv/oauth2/token', body)
#data output
keys = r.json();
headers = {
'Client-ID': client_id,
'Authorization': 'Bearer ' + keys['access_token']
}
while True:
global stream_data
stream = requests.get('https://api.twitch.tv/helix/streams?user_login=' + streamer_name, headers=headers)
stream_data = stream.json()
return stream_data
Command to start for cycle
#bot.message_handler(commands=['stream'])
def id(message):
adm = [1720942952]
if message.from_user.id in adm:
while True:
checkstream()
strdata = stream_data
if len(stream_data['data']) == 1:
bot.send_message(message.chat.id, f'{streamer_name} is live: {strdata["data"][0]["title"]} playing {strdata["data"][0]["game_name"]}') #sending a message in telegram
else:
pass
Here it is necessary that a message is sent once when the Twitch stream is launched
I tried sending email using python and put attachment, but when it sent the attachment became noname without any extension.
message = MIMEMultipart()
message ['From'] = sender_email
message ['To'] = ', '.join(receiver_email)
message ['Subject'] = 'Python Email'
message.attach(MIMEText(mail_content, 'plain'))
attach_file_name = 'Final Project - Basic Python.pdf'
attach_file = open('Final Project - Basic Python.pdf', 'rb')
payload = MIMEBase('application', 'octate-stream')
payload.set_payload((attach_file).read())
encoders.encode_base64(payload)
payload.add_header('Content-Decomposition', 'attachment', filename=attach_file_name)
message.attach(payload)
def getbodyinbox():
service = build('gmail', 'v1', credentials=creds)
label_name = "READ-BY-SCRIPT"
label_id = 'Label_8507504117657095973'
results = service.users().messages().list(
userId='me', q="-label:"+label_name, maxResults=1).execute()
messages = results.get('messages', [])
body = []
if not messages:
body = "no messages"
return body
else:
for message in messages:
msg = service.users().messages().get(
userId='me', id=message['id']).execute()
labels = msg['labelIds']
if "INBOX" in labels:
headers = msg['payload']['headers']
headers = str(headers)
print(headers)
if "class_ix" in headers:
body.append(msg['payload']['parts'])
if 'data' in body[0][0]['body']:
body = base64.urlsafe_b64decode(
body[0][0]['body']['data'])
elif 'data' in body[0][1]['body']:
body = base64.urlsafe_b64decode(
body[0][1]['body']['data'])
body = str(body)
return body
print(getbodyinbox())
This is my code so far with the part that gets the credentials and all of the imports removed. It gets the body of the most recent email without a label 'READ-BY-SCRIPT' that also has the label INBOX. How can I get the subject of the email instead of the body?
Have a look at the message resource, MessagePart and header
The structure is the following:
"payload": {
"partId": string,
"mimeType": string,
"filename": string,
"headers": [
{
"name": string,
"value": string
}
],
and:
So, in other words, the subject is contained in the headers.
You can retrieve in Python with
headers = msg['payload']['headers']
subject= [i['value'] for i in headers if i["name"]=="Subject"]
I'm trying to send an email via the Gmail API using Python, I want to iclude the signature. I'm able to successfuly get the signature using the following funciotn:
def addSignature(service):
sigtanture = service.users().settings().sendAs().get(userId=USER, sendAsEmail='example#example.com').execute()
return sigtanture['signature']
addSignature(SERVICE)
However, at the time of creating the message that I'll send, how do I append the Signature?
def CreateMessage(sender, to, subject, message_text, signature):
message = MIMEMultipart('alternative')
message['to'] = to
message['from'] = sender
message['subject'] = subject
message[???] = signature
raw = base64.urlsafe_b64encode(message.as_bytes())
raw = raw.decode()
body = {'raw': raw}
return body
I'm trying to send the message:
thebody = CreateMessage(USER, 'to#example.com', 'TestSignatureAPI','testing', addSignature(SERVICE))
SendMessage(SERVICE, USER, thebody)
Thank you!
Unfortunately there is no built-in feature to append the Gmail signature to your email
Instead, once you retrieve your signature as a text, you can simply append it manually to the end of your message_text before encoding.
See also here.
Assuming you retrieved the signature correctly and based on your code this means:
def CreateMessage(sender, to, subject, message_text, signature):
message_text = message_text + "\n" + signature
message = MIMEMultipart('alternative')
message['to'] = to
message['from'] = sender
message['subject'] = subject
message.attach(MIMEText(message_text_plain, 'plain'))
raw = base64.urlsafe_b64encode(message.as_bytes())
raw = raw.decode()
body = {'raw': raw}
return body
I am new to python. I am trying to send a response showing a custom keyboard with two buttons to the user in Telegram app but it gives me an error about encode.
I would like to know where is my mistake.
import json
from urllib.request import urlopen
from urllib.parse import quote, unquote
import time
def Decode(telegram_response):
decoded=''
for line in telegram_response:
decoded=decoded+line.decode('utf-8')
return decoded
TOKEN = 'mytoken'
URL = 'https://api.telegram.org/bot{}/'.format(TOKEN)
cmd = 'getme'
telegram_response = urlopen(URL + cmd)
decoded = Decode(telegram_response)
gtm = json.loads(decoded)
status = True
while status:
cmd = 'getUpdates'
telegram_response = urlopen(URL + cmd)
decoded = Decode(telegram_response)
upds = json.loads(decoded)
new_message = len(upds['result'])
if new_message !=0:
msg = upds['result'][0]['message']
chat_id = str(msg['chat']['id'])
reply_markup = {'keyboard': [[{'text':'first button'}],[{'text':'second button'}]], 'resize_keyboard': True, 'one_time_keyboard': True}
reply_markup = json.dumps(reply_markup)
params = ({'chat_id': chat_id, 'reply_markup': reply_markup, 'disable_web_page_preview': 'true'})
myresponse =urlopen(URL + 'sendMessage' + quote((params).encode('utf-8')))
Easy way to build powerful bots is to use python-telegram-bot library.
I re-writed your code with few major fixes and features. Hope it help you to learn bots more deeper.
my version of bot:
###############################################################################
!#/usr/bin/python3
from sys import exc_info as error
from urllib.request import urlopen
from urllib.parse import urlencode
import json
TOKEN = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX'
URL = 'https://api.telegram.org/bot{}'.format(TOKEN)
STATUS = True
OFFSET = 0
def call_api_method(method='getMe', data=None):
# Call API method with data.
data = urlencode(data).encode("utf-8") if data else data
response = urlopen('{}/{}'.format(URL, method), data)
return json.loads(response.read())
def get_me():
# Get bot info.
bot = call_api_method()
return type('Bot', (), dict(bot['result']))
def get_updates():
# Get new updates from Telegram.
data = {'offset': OFFSET, 'limit': 0, 'timeout': 0}
return type('Updates', (), call_api_method('getUpdates', data))
def handle(update):
# Make usefull objects.
message = type('Message', (object,), dict(update['message']))
user = type('User', (), dict(update['message']['from']))
chat = type('Chat', (), dict(update['message']['chat']))
return message, user, chat
def send_message(chat_id, message):
# Send message to specific chat.
data = {'text': message,
'chat_id': chat_id,
'parse_mode': 'Markdown',
'disable_web_page_preview': True}
call_api_method('sendMessage', data)
def send_keyboard(chat_id, message, keyboard):
# Send message and keyboard to specific chat.
data = {'text': message,
'chat_id': chat_id,
'parse_mode': 'Markdown',
'reply_markup': reply_markup(keyboard),
'disable_web_page_preview': 'true'}
call_api_method('sendMessage', data)
def reply_markup(keyboard):
# Serialize keyboard data to JSON.
return json.dumps({'keyboard': keyboard,
'resize_keyboard': True,
'one_time_keyboard': True,
'selective': True})
def main_keyboard():
# Main menu.
return [first_button(), second_button()]
def one_line_keyboard():
# Menu with buttons in one line.
return [two_buttons()]
def first_button():
# Single keyboard button.
return ['first button']
def second_button():
# Single keyboard button.
return ['second button']
def two_buttons():
# Two buttons on one line.
return ['left button', 'right button']
while STATUS:
# Get updates forever. Except if get Error.
try:
if not OFFSET:
OFFSET = 1
# Print bot info on the start.
bot = get_me()
print('Bot #{} is running...'.format(bot.username))
updates = get_updates()
for update in updates.result:
# Handle last update.
OFFSET = update['update_id'] + 1
message, user, chat = handle(update)
# Greeting user by full name.
greeting = 'Hello, {} {}!'.format(user.first_name, user.last_name)
#send_message(chat.id, greeting)
send_keyboard(chat.id, greeting, one_line_keyboard())
except:
STATUS = False
print('\nERROR:\t', error()[1])
###############################################################################
you can this code: I hope useful for you .
i change :
params = ({'chat_id': chat_id, 'reply_markup': reply_markup, 'disable_web_page_preview': 'true'})
myresponse =urlopen(URL + 'sendMessage' + quote((params).encode('utf-8')))
with:
params = ({'text': 'ss', 'chat_id': chat_id, 'reply_markup': reply_markup, 'disable_web_page_preview': 'true'})
data = urllib.parse.urlencode(params).encode("utf-8")
myresponse = urlopen(URL + 'sendMessage', data)
complate code :
import json
import urllib
from urllib.parse import quote
from urllib.request import urlopen
def Decode(telegram_response):
decoded = ''
for line in telegram_response:
decoded = decoded + line.decode('utf-8')
return decoded
TOKEN = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX'
URL = 'https://api.telegram.org/bot{}/'.format(TOKEN)
cmd = 'getme'
telegram_response = urlopen(URL + cmd)
decoded = Decode(telegram_response)
gtm = json.loads(decoded)
status = True
while status:
cmd = 'getUpdates'
telegram_response = urlopen(URL + cmd)
decoded = Decode(telegram_response)
upds = json.loads(decoded)
new_message = len(upds['result'])
if new_message != 0:
msg = upds['result'][0]['message']
chat_id = str(msg['chat']['id'])
reply_markup = {'keyboard': [[{'text': 'first button'}], [{'text': 'second button'}]], 'resize_keyboard': True,
'one_time_keyboard': True}
reply_markup = json.dumps(reply_markup)
params = ({'text': 'ss', 'chat_id': chat_id, 'reply_markup': reply_markup, 'disable_web_page_preview': 'true'})
data = urllib.parse.urlencode(params).encode("utf-8")
myresponse = urlopen(URL + 'sendMessage', data)