I am new to python and having trouble with the following code, I know it has something to do with the self keyword but I am unsure what I am doing wrong.
main code:
user_operation = UserOperations(headers)
user = user_operation.get_user(arguments['source'],arguments['id'])
user_operations:
class UserOperations(object):
def __init__(self, headers):
self.headers = headers
def get_user(self, account_id, user_id):
#Get user
user = requests.get(api_root + "/accounts/" + account_id + "/users/" + user_id, headers=headers)
#Throw exception if non-200 response
user.raise_for_status()
print "\nGet User " + user_id + ": " + user.text
#Check user exists
if user.json()['Data'] is None:
return None
#Return user
return user.json()['Data']
Error:
Traceback (most recent call last):
File "py-front.py", line 117, in <module>
user = user_operation.get_user(arguments['<source>'],arguments['<id>'])
TypeError: get_user() takes exactly 2 arguments (3 given)
Any help would be appreciated!
Related
I'm not very experienced programming in Python but I've also seen in several posts that this problem might be solved by adding self to the method definition. The problem is that I actually already did this right from the beginning. This is the code I'm using:
### API MANAGER ###
class api_manager():
import requests, time, pandas as pd
#from ipython.display import display, HTML
# heroes = []
# items = []
# token = ''
# url = ""
def __init__(self, api_identifier = 1):
test_api_url = "https://api.steampowered.com/IDOTA2Match_570/"
live_api_url = "https://api.steampowered.com/IDOTA2Match_205790/"
self.heroes = []
self.items = []
self.token = ''
self.url = ""
if api_identifier == 1:
self.url = live_api_url
else:
self.url = test_api_url
self.get_access_token()
self.initialize_heroes()
self.initialize_items()
pass
def get_access_token(self):
with open("conf/access.config") as file:
self.token = file.read().split(":")[1]
file.close
pass
def initialize_heroes(self):
response = self.requests.get(self.url + "GetHeroes/v1/?format=JSON&language=en_us&key=" + self.token)
hero_list = response.json()
for hero_id in range(len(hero_list['result']['heroes'])):
self.heroes.append([hero_list['result']['heroes'][hero_id]['id'], hero_list['result']['heroes'][hero_id]['localized_name'], hero_list['result']['heroes'][hero_id]['name'].replace('npc_dota_hero_', "").replace("_", " ")])
self.heroes.sort()
heroes_df = self.pd.DataFrame(self.heroes, columns=["ID", "Hero", "Hero Tag"])
self.pd.set_option('display.max_colwidth', -1)
#display(HTML(heroes_df.to_html(index = False)))
pass
def initialize_items(self):
response = self.requests.get(self.url + "GetGameItems/v1/?format=JSON&language=en_us&key=" + self.token)
item_list = response.json()
for item_id in range(len(item_list['result']['items'])):
self.items.append([item_list['result']['items'][item_id]['id'], item_list['result']['items'][item_id]['localized_name'], response.json()['result']['items'][item_id]['name']])
self.items.sort()
items_df = self.pd.DataFrame(self.items, columns=["ID", "Item", "Item Tag"])
self.pd.set_option('display.max_colwidth', -1)
#display(HTML(items_df.to_html(index = False)))
pass
def get_match_details(match_id, self):
response = self.requests.get(self.url + "GetMatchDetails/V001/?format=JSON&language=en_us&key=" + self.token + "&match_id=" + str(match_id))
print(response.json())
pass
def get_match_details_in_range(match_id, match_id_upper_bound, self):
for next_match_id in range(match_id, match_id_upper_bound):
response = self.requests.get(self.url + "GetMatchDetails/V001/?format=JSON&language=en_us&key=" + self.token + "&match_id=" + str(next_match_id))
print(response.json())
self.time.sleep(1.05)
pass
And this is the error I'm getting in Python3 console run in Windows cmd:
>>> instance = api_manager()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "E:\Dropbox\DotA 2 WebAPI Development\Executable Python Files\dota_api_manager.py", line 22, in __init__
self.get_access_token()
TypeError: get_access_token() takes 0 positional arguments but 1 was given
I don't know what exactly I'm doing wrong. I already tried different things in my code but never got it to actually work. There was one moment when the code executed properly and I could actually call the method get_match_details() but I got an error because the url parameter was not set for whatever reason, although it should have been initialized right in the beginning of __init__().
Thanks in advance for your help and let me know if you need any additional information.
So, I'm a bit new with the Python code so I'm a bit lost when trying to decypher the issue here.
I keep getting this error when trying to run this module:
Traceback (most recent call last):
File "C:\Users\test\OneDrive\Documents\mass.py", line 33, in <module>
delete_all(auth_token, channel_id, username1, username2, get_all_messages(auth_token, channel_id))
File "C:\Users\test\OneDrive\Documents\mass.py", line 29, in delete_all
if (message["author"]["username"] == user1):
KeyError: 'author'
Here's all of the code right here:
import json, requests, sys
print ("Delete all messages from specific channel")
username1 = "test"
username2 = "test#0101"
auth_token = "ZMNHFHFKJkjfja.FJDJfhsd.EJjfda"
channel_id = "35345345345451"
delete_from_all_users = "False"
def get_all_messages(auth, id, last="", prev=[]):
if not last:
messages = json.loads(requests.get("http://canary.discordapp.com/api/v6/channels/" + id + "/messages", headers={"authorization": auth}, params={"limit": 100}).content)
else:
messages = json.loads(requests.get("http://canary.discordapp.com/api/v6/channels/" + id + "/messages", headers={"authorization": auth}, params={"before" : last, "limit" : 100}).content)
prev.append(messages)
if len(messages) < 100:
print ("Got to end of channel at " + str(len(prev)) + " messages")
return prev
else:
oldest = sorted(messages, key=lambda x: x["timestamp"], reverse=True)[-1]
return get_all_messages(auth, id, last=oldest["id"], prev=prev)
def delete_all(auth, id, user1, user2, messages):
print ("Trying to delete all messages in " + id + " from username " + user1)
for message in messages:
# print(message["author"]["username"])
if (message["author"]["username"] == user1):
requests.delete("http://canary.discordapp.com/api/v6/channels/" + id + "/messages/" + message["id"],headers={"authorization": auth})
print ("All messages were deleted")
delete_all(auth_token, channel_id, username1, username2, get_all_messages(auth_token, channel_id))
Kelsey, in your code in the 4th last line in the if condition,
if (message["author"]["username"] == user1):
the compiler does not find any "author" in the json messages that you are iterating upon. Now since we do not know the structure of your json we cannot help you out more there, but this is for sure that the message json does not contain any key such namely author.
I tried to look up this issue, but it seems like I've done something I can no longer look up on my own, so I'll need your guys' help. This will probably be a rather difficult one, but I really hope that someone will help me with this one!
The code: (Apologies for the messy code beforehand)
import json, requests, threading, discord, math, random
from requests import adapters
from requests_testadapter import Resp
from discord.ext.commands import Bot
TOKEN = 'SOMETOKENIDTHATICANTREVEALANDYOUKNOWWHY'
BOT_PREFIX = ('!')
url_api = 'http://api.lambdawars.com/player/matches/list/{}' # input the
SteamID64
client = Bot(command_prefix=BOT_PREFIX)
#client.async_event
class LocalFileAdapter(requests.adapters.HTTPAdapter):
def build_response_from_file(self,request,steamid):
file_path = request.url_api.format(steamid)[7:]
with open(file_path, 'rb') as file:
buff = bytearray(file.read())
resp = Resp(buff)
r = self.build_response(request, resp)
return r
def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):
return self.build_response_from_file(request)
requests_session = requests.session()
requests_session.mount('file://', LocalFileAdapter())
old_response = ''
monitor_ids = []
#client.command(name='addID')
async def monitoring(steamid):
global old_response
monitor_ids.append(steamid)
while True:
await client.say("Loading results for: " + steamid + "...")
print('Loading results for: ' + steamid)
url_new = url_api
response = requests_session.get(url_new.format(steamid))
if response != old_response:
old_response = response
try:
global idresponse
idresponse = str('-\nPlayer ID {} **' + response.json()['matches'][0]['end_state'] + "** on **" +
response.json()['matches'][0]['start_date'] + "** on map **" + response.json()['matches'][0][
'map'] + "**. \nGame mode: **" + response.json()['matches'][0]['mode'] + "**, type: **" +
response.json()['matches'][0]['type'] + "**. \nThe match lasted **" + str(
math.floor(float(response.json()['matches'][0]['duration']) / 60)) + "** minutes").format(id)
except TypeError:
print("duration type error - bust be a number")
# await client.say(' | '.join(god_damnit_sandern))
await client.say(random.choice["God damnit, Sandern! That match failed to be recorded properly. " + '<:hmm:453711378067226630>',
"God damnit, Sandern! He stole your match data!" + '<:hmm:453711378067226630>',
"God damnit, Sandern! Your match data was not found, it's all his fault!" + '<:hmm:453711378067226630>'])
except KeyError:
print("Wrong SteamID64 number!")
# await client.say('|'.join(god_damnit_sandern))
await client.say("-"
"\nThis (" + steamid + ") isn't SteamID64. <:hardfacepalm:453711378272878592> "
"\nCheck for typos?")
except IndexError:
print("This SteamID64 has no game records.")
await client.say('-'
'\nThis user (' + steamid + ') has never ever played Lambda Wars online yet! <:youserious:453711378687983626>'
'\nWhat a loser!')
await client.say(idresponse)
thread = threading.Thread(target=monitoring)
thread.start()
client.run(TOKEN)
I was working on a Discord bot. The idea was to make a command, namely !addID 76561197995806465 where the ID itself is a SteamID64 for tracking API results on the following page: http://api.lambdawars.com/player/matches/list/76561197995806465
This is basically a JSON result with some of its pieces taken out from the first bit (['matches'][0][{a key, such as "duration" or "start_date"}]).
The plan was to make it automatically get the results, as soon as these results are given, using the following piece in the monitoring method:
if response != old_response:
old_response = response
It does work as a command and makes the Discord bot leave a message when given the SteamID64 and an optional number, such as 1 (0 being default):
LamBOTa Wars: -
Player ID 76561198223952276 lost on Sat, 16 Jun 2018 10:23:49 GMT on map hlw_breakout.
Game mode: destroyhq, type: FFA.
The match lasted 13 minutes
(If you would like to see the code for this one, I'll post it)
So when I run my code, I get the following:
Exception in thread Thread-1:
Traceback (most recent call last):
File "D:\Program Files\Python\Python3\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "D:\Program Files\Python\Python3\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
TypeError: 'Command' object is not callable
Help would be really appreciated!
Also before you ask, yes, I am a newb at programming in general. That's my first experience with bots.
i know that a lot of people have asked related questions but please help me out. I am trying to replicate an opensource temperature control lab i found online. I wanted to run it on Raspberry Pi.
This is the error i keep getting:
Traceback (most recent call last):
File "/home/pi/Desktop/Python/test_Temperature.py", line 14, in <module>
print('Temperature 1: ' + str(a.T1) + ' degC')
File "/home/pi/Desktop/Python/tclab.py", line 26, in T1
self._T1 = float(self.read('T1'))
TypeError: float() argument must be a string or a number, not 'NoneType'
The code that generates it is this:
import tclab
import numpy as np
import time
try:
# Connect to Arduino
a = tclab.TCLab()
# Get Version
print(a.version)
# Temperatures
print('Temperatures')
print('Temperature 1: ' + str(a.T1) + ' degC')
print('Temperature 2: ' + str(a.T2) + ' degC')
# Turn LED on
print('LED On')
a.LED(100)
# Turn on Heaters (0-100%)
print('Turn On Heaters (Q1=90%, Q2=80%)')
a.Q1(90.0)
a.Q2(80.0)
# Sleep (sec)
time.sleep(60.0)
# Turn Off Heaters
print('Turn Off Heaters')
a.Q1(0.0)
a.Q2(0.0)
# Temperatures
print('Temperatures')
print('Temperature 1: ' + str(a.T1) + ' degC')
print('Temperature 2: ' + str(a.T2) + ' degC')
# Allow user to end loop with Ctrl-C
except KeyboardInterrupt:
# Disconnect from Arduino
a.Q1(0)
a.Q2(0)
print('Shutting down')
a.close()
# Make sure serial connection still closes when there's an error
except:
# Disconnect from Arduino
a.Q1(0)
a.Q2(0)
print('Error: Shutting down')
a.close()
raise
I believe the code seeks to communicate with another python file with the below code:
import sys
import time
import numpy as np
try:
import serial
except:
import pip
pip.main(['install','pyserial'])
import serial
from serial.tools import list_ports
class TCLab(object):
def __init__(self, port=None, baud=9600):
if (sys.platform == 'darwin') and not port:
port = '/dev/ttyACM1'
def stop(self):
return self.read('X')
def version(self):
return self.read('VER')
#property
def T1(self):
self._T1 = float(self.read('T1'))
return self._T1
#property
def T2(self):
self._T2 = float(self.read('T2'))
return self._T2
def LED(self,pwm):
pwm = max(0.0,min(100.0,pwm))/2.0
self.write('LED',pwm)
return pwm
def Q1(self,pwm):
pwm = max(0.0,min(100.0,pwm))
self.write('Q1',pwm)
return pwm
def Q2(self,pwm):
pwm = max(0.0,min(100.0,pwm))
self.write('Q2',pwm)
return pwm
# save txt file with data and set point
# t = time
# u1,u2 = heaters
# y1,y2 = tempeatures
# sp1,sp2 = setpoints
def save_txt(self,t,u1,u2,y1,y2,sp1,sp2):
data = np.vstack((t,u1,u2,y1,y2,sp1,sp2)) # vertical stack
data = data.T # transpose data
top = 'Time (sec), Heater 1 (%), Heater 2 (%), ' \
+ 'Temperature 1 (degC), Temperature 2 (degC), ' \
+ 'Set Point 1 (degC), Set Point 2 (degC)'
np.savetxt('data.txt',data,delimiter=',',header=top,comments='')
def read(self,cmd):
cmd_str = self.build_cmd_str(cmd,'')
try:
self.sp.write(cmd_str.encode())
self.sp.flush()
except Exception:
return None
return self.sp.readline().decode('UTF-8').replace("\r\n", "")
def write(self,cmd,pwm):
cmd_str = self.build_cmd_str(cmd,(pwm,))
try:
self.sp.write(cmd_str.encode())
self.sp.flush()
except:
return None
return self.sp.readline().decode('UTF-8').replace("\r\n", "")
def build_cmd_str(self,cmd, args=None):
"""
Build a command string that can be sent to the arduino.
Input:
cmd (str): the command to send to the arduino, must not
contain a % character
args (iterable): the arguments to send to the command
"""
if args:
args = ' '.join(map(str, args))
else:
args = ''
return "{cmd} {args}\n".format(cmd=cmd, args=args)
def close(self):
try:
self.sp.close()
print('Arduino disconnected successfully')
except:
print('Problems disconnecting from Arduino.')
print('Please unplug and reconnect Arduino.')
return True
I do not know my around python codes yet so a very clear 'for dummy class' explanation of the solution would really help. Thanks guys.
This is the read() function:
def read(self,cmd):
cmd_str = self.build_cmd_str(cmd,'')
try:
self.sp.write(cmd_str.encode())
self.sp.flush()
except Exception:
return None
return self.sp.readline().decode('UTF-8').replace("\r\n", "")
One of the things it can return is None as you can see in the return None line. If that happens, then your line:
float(self.read('T1'))
will fail, because it will try to convert None into a float, and that gives the error you're getting.
I am running a simple python server application with grpc. This is the server code:
class Classifier(grpc_cl.BetaClassifierServicer):
def __init__(self):
default_config = self.getDefaultConfig()
self.engine_config = default_config["engine"]
self.port = default_config["daemon"]["port"]
# self.engine = loadLSTM3Model(self.engine_config)
def getDefaultConfig(self):
with open("service.properties.yaml", "r") as stream:
default_config = yaml.load(stream)
return default_config
def Analyze(self, request, context):
file_name = request.sentences_file
print "This is the file to analyze ", file_name
error = grpc_cl.Error(error_code = 0, error_message = "OK")
return grpc_cl.CategoryReply(error)
The client:
channel = implementations.insecure_channel('localhost', 50051)
stub = classifier_grpc.beta_create_Classifier_stub(channel)
reply = stub.Analyze(classifier_grpc.CategoryRequest(user_context=1, sentences_file="file"), 10000)
print 'Answer', reply.error.error_message
And the .proto file with the messages:
syntax = "proto3";
service Classifier{
rpc Analyze(CategoryRequest) returns (CategoryReply){}
rpc Train(TrainRequest) returns (CategoryReply){}
}
message CategoryRequest{
int32 user_context = 1;
string sentences_file = 2;
}
message CategoryReply{
Error error = 1;
string categories_file = 2;
}
message Error{
int32 error_code = 1;
string error_message = 2;
}
Launching the server and the client, and connecting both of them to the respective port, gives me this error:
Traceback (most recent call last):
File "/home/~/service/client.py", line 19, in <module>
reply = stub.Analyze(classifier_grpc.CategoryRequest(user_context=1, sentences_file="file"), 10000)
File "/usr/local/lib/python2.7/dist-packages/grpc/framework/crust/implementations.py", line 73, in __call__
protocol_options, metadata, request)
File "/usr/local/lib/python2.7/dist-packages/grpc/framework/crust/_calls.py", line 109, in blocking_unary_unary
return next(rendezvous)
File "/usr/local/lib/python2.7/dist-packages/grpc/framework/crust/_control.py", line 412, in next
raise self._termination.abortion_error
grpc.framework.interfaces.face.face.RemoteError
Does somebody now why this happens? Also, I could extract the user_context from the CategoryRequest, but not the sentences_file string, that one is blank.
grpc.framework.interfaces.face.face.RemoteError indicates that an exception occurred on the server while processing the request.
In your case, protobuf parameters need to be specified by keyword, ie
return grpc_cl.CategoryReply(error)
should be
return grpc_cl.CategoryReply(error=error)