Sending a message once without breaking the cycle - python-3.x

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

Related

bithumb Api error -{'status': '5100', 'message': 'Bad Request.(Auth Data)'}

I wanted to make a program where I can check the order details of my order at Bithumb Exchange.
So I looked at the docs(https://api.bithumb.com/info/orders) and made it, but the same error code kept coming out, so I don't know what to do.
import time
import math
import base64
import hmac, hashlib
import urllib.parse
import requests
class XCoinAPI:
api_url = "https://api.bithumb.com";
api_key = "";
api_secret = "";
def __init__(self, api_key, api_secret):
self.api_key = api_key;
self.api_secret = api_secret;
def body_callback(self, buf):
self.contents = buf;
def microtime(self, get_as_float = False):
if get_as_float:
return time.time()
else:
return '%f %d' % math.modf(time.time())
def usecTime(self) :
mt = self.microtime(False)
mt_array = mt.split(" ")[:2];
return mt_array[1] + mt_array[0][2:5];
def xcoinApiCall(self, endpoint, rgParams):
# 1. Api-Sign and Api-Nonce information generation.
# 2. Request related information from the Bithumb API server.
#
# - nonce: it is an arbitrary number that may only be used once.
# - api_sign: API signature information created in various combinations values.
endpoint_item_array = {
"endpoint" : endpoint
}
uri_array = dict(endpoint_item_array, **rgParams) # Concatenate the two arrays.
str_data = urllib.parse.urlencode(uri_array)
nonce = self.usecTime()
data = endpoint + chr(1) + str_data + chr(1) + nonce
utf8_data = data.encode('utf-8')
key = self.api_secret
utf8_key = key.encode('utf-8')
h = hmac.new(bytes(utf8_key), utf8_data, hashlib.sha512)
hex_output = h.hexdigest()
utf8_hex_output = hex_output.encode('utf-8')
api_sign = base64.b64encode(utf8_hex_output)
utf8_api_sign = api_sign.decode('utf-8')
headers = {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
"Api-Key": self.api_key,
"Api-Nonce": nonce,
"Api-Sign": utf8_api_sign
}
url = self.api_url + endpoint
r = requests.post(url, headers=headers, data=uri_array)
return r.json()
a = XCoinAPI(api_key="MYKEY1c", api_secret="MYKEY2")
aa= a.xcoinApiCall("/info/orders",{"order_currency":"LN","payment_currency":"BTC"})
print(aa)
{'status': '5100', 'message': 'Bad Request.(Auth Data)'}
Process finished with exit code 0
The error code 5100, bad request keeps coming up(https://apidocs.bithumb.com/docs/api-%EC%A3%BC%EC%9A%94-%EC%97%90%EB%9F%AC-%EC%BD%94%EB%93%9C)
I really don't know which code to modify.
I think it's a parameter problem with XcoinApiCall, but I don't know.

How can i used google drive api v3 to upload a file to shared drive

I am trying to upload a file to my shared drive using drive API v3
it works fine with normal drive ids, but when I put shared drive ids, it fails to work.
my code :-
#!/usr/bin/python3
import argparse
import json
import mimetypes
import os.path
import requests
script_path = os.path.abspath(__file__)
script_dir = os.path.dirname(script_path)
parser = argparse.ArgumentParser()
parser.add_argument('file', metavar='FILE')
parser.add_argument('folder', metavar='FOLDER_ID')
parser.add_argument('-v', '--verbose', action='store_true')
args = parser.parse_args()
file_path = args.file
file_obj = open(file_path, mode='rb')
file_name = os.path.basename(file_path)
file_mime_type = mimetypes.guess_type(file_path)[0]
### client secret ###
client = None
client_name = 'client_secret.json'
client_path = os.path.join(script_dir, client_name)
with open(client_path, 'r') as f:
client = json.load(f)
assert client is not None and 'installed' in client
client = client['installed']
assert 'client_id' in client
if args.verbose:
print('=== client id ===')
print(client['client_id'])
print()
assert 'client_secret' in client
if args.verbose:
print('=== client secret ===')
print(client['client_secret'])
print()
### refresh token ###
refresh_token = None
refresh_name = 'refresh_token.txt'
refresh_path = os.path.join(script_dir, refresh_name)
with open(refresh_path, mode='r') as f:
refresh_token = f.read().rstrip()
if args.verbose:
print('=== refresh token ===')
print(refresh_token)
print()
### access token ###
r = requests.post('https://accounts.google.com/o/oauth2/token', data={
'client_id': client['client_id'],
'client_secret': client['client_secret'],
'refresh_token': refresh_token,
'grant_type': 'refresh_token',
})
r = r.json()
assert 'error' not in r, r['error_description']
access_token = r['access_token']
if args.verbose:
print('=== access token ===')
print(access_token)
print()
### upload file ###
r = requests.post('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart', files={
'metadata': (
None, json.dumps({
'name': file_name,
'parents': [
args.folder,
],
}),
'application/json; charset=UTF-8'
),
'file': (
file_name,
file_obj,
file_mime_type,
),
}, headers={
'Authorization': 'Bearer ' + access_token,
})
r = r.json()
assert 'error' not in r, '{} - {}'.format(r['error']['code'], r['error']['message'])
if args.verbose:
print('=== file id ===')
print(r['id'])
print()
(sorry for messy code file handling is messy)
I cant find any documentation which helps to create requests for shared drives
I just want it to work when I put a shared drive id as well
please suggest changes :)
Turns out all i had to do was put "&supportsAllDrives=true" after "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart"

Can I use urlencode in python to insert a string of characters into this Spotify API request?

I am working with Spotify API to request song data through a URL. I imported urlencode to run the song's ID as a function parameter into the url. Essentially, I need the ID portion of the url request to be the ID by itself, not "id=<id string>"
I tried assigning the id string to a parameter of my 'search' function. The search function takes a user input song ID from spotify, inserts it into the proper position in the URL request, and sends it to the spotify database to retrieve that songs data analysis. The program successfully sends out the request, but the id portion I am filling in puts "id=<song ID>" instead of the song ID by itself.
import requests
import datetime
from urllib.parse import urlencode
# In[3]:
import base64
# In[4]:
client_id = 'fb5af83351d4402fa82904fc04f7fc9e'
client_secret = 'b5057eb39b024180b61b02eb45fb97a6'
# In[5]:
class SpotifyAPI(object):
access_token = None
access_token_expires = datetime.datetime.now()
access_token_did_expire = True
client_id = None
client_secret = None
token_url = "https://accounts.spotify.com/api/token"
def __init__(self, client_id, client_secret, *args, **kwargs):
super().__init__(*args, **kwargs)
self.client_id = client_id
self.client_secret = client_secret
def get_client_credentials(self):
client_id = self.client_id
client_secret = self.client_secret
if client_secret == None or client_id == None:
raise Exception("You must set client_id and client_secret")
client_creds = f"{client_id}:{client_secret}"
client_creds_b64 = base64.b64encode(client_creds.encode())
return client_creds_b64.decode()
def get_token_headers(self):
client_creds_b64 = self.get_client_credentials()
return {
"Authorization": f"Basic {client_creds_b64}"
}
def get_token_data(self):
return {
"grant_type": "client_credentials"
}
def perform_authorization(self):
token_url = self.token_url
token_data = self.get_token_data()
token_headers = self.get_token_headers()
r = requests.post(token_url, data=token_data, headers=token_headers)
print(r.json())
if r.status_code not in range(200,299):
raise Exception("Could not authenticate client")
#return False
data = r.json()
now = datetime.datetime.now()
access_token = data['access_token']
expires_in = data['expires_in'] #seconds
expires = now + datetime.timedelta(seconds=expires_in)
self.access_token = access_token
self.access_token_expires = expires
self.access_token_did_expire = expires < now
return True
def get_access_token(self):
token = self.access_token
expires = self.access_token_expires
now = datetime.datetime.now()
if expires < now:
self.perform_authorization()
return self.get_access_token()
elif token == None:
self.perform_authorization()
return self.get_access_token()
return token
def search(self, id):
access_token = self.get_access_token()
headers = {
"Authorization": f"Bearer {access_token}"
}
end_point = "https://api.spotify.com/v1/audio-analysis/"
data = urlencode({"id":id})
print(data)
lookup_url = f"{end_point}{data}"
print(lookup_url)
r = requests.get(lookup_url, headers = headers)
if r.status_code not in range(200, 299):
return r
return r.json()
it returns
{'access_token': 'BQCLoKT_b2PF7KPSbscosa1dCpE5rzd_RBkswOvwklVdlAL4AeEGCDn0iYuqac5o86BTqCIz0m95u3olLp4', 'token_type': 'Bearer', 'expires_in': 3600}
id=1UGD3lW3tDmgZfAVDh6w7r
https://api.spotify.com/v1/audio-analysis/id=1UGD3lW3tDmgZfAVDh6w7r

How can we terminate the locust process based on num of requests?

I have to do load test using locust.io for multiple APIs, so I want to execute 10 requests for each and every API (suppose I have 10 APIs , so each and every API should get 10 requests) and should terminate the process automatically if all requests were done.
Below is the code snippet i have tried using for loop but not yet worked.
class UserBehavior(TaskSet):
def __init__(self, parent):
super().__init__(parent)
self.camp_code = random.choice(t.camp_code)
self.pgm_id = random.choice(t.pgm_id)
#task
def alloction_details(self):
pgm_id = self.pgm_id
camp_code = self.camp_code
print("L21",camp_code)
myheaders = {'Content-Type': 'application/json', 'Accept': 'application/json'}
load = {
"Code": str(camp_code),
"Id": str(pgm_id)}
# print("L43", users)
for i in range(10):
if i==9:
self.interrupt()
else:
with self.client.post('/ContentDetails', data= json.dumps(load), headers=myheaders,catch_response=True) as response:
print(response.status_code)
if response.status_code==200:
response.success()
# res = response.json()
print("Response of allocation details ", response.text, '\n\n')
else:
response.failure('API failure')
#task
def get_content_details(self):
myheaders = {'Content-Type': 'application/json', 'Accept': 'application/json'}
pgm_id = self.pgm_id
camp_code = self.camp_code
for i in range(10):
if i == 9:
# sleep(1000)
self.interrupt()
else:
with self.client.post('/ScheduleDetails?Code='+str(camp_code), catch_response=True) as response:
print(response.status_code)
if response.status_code==200:
response.success()
# res = response.json()
print("Response : ", response.text, '\n\n')
else:
response.failure('API failure')
class WebsiteUser(HttpUser):
tasks = [UserBehavior]
host = 'localhost'
wait_time = between(1, 3)

Python Telegram API ReplyKeyboardMarkup

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)

Resources