Python exchangelib raise ValueERROR datetime_received - python

I'm trying to check how many emails have been received from the specified sender.email_address the past 24 hours, but I get an error from this code
Traceback (most recent call last):
File "c:/Users/fmi/Desktop/Python/emailtest.py", line 13, in
for item in testfolder.all()
File "C:\Users\fmi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\exchangelib\queryset.py", line 507, in order_by
raise ValueError("%s in order_by()" % e.args[0])
ValueError: Unknown field path '-datetime_recieved' on folders [Messages(Root(<exchangelib.account.Account object at 0x020A81F0>, '[self]', 'root', 8, 0, 62, None, 'AQMkADI2YmY4MjAwAC1mNTBkLTQyMzEtYTM0Yi04NTdmZDRhMDE0MGQALgAAA+xnYBMGPANEmpY/yEHuM6wBAEYSp+OGVQhHl3U8WgJ/ZQAAAwEBAAAAAA==', 'AQAAABYAAABGEqfjhlUIR5d1PFoCf2UAAAAcRKyn'), 'Test', 26821, 26654, 0, 'IPF.Note', 'AQMkADI2YmY4MjAwAC1mNTBkLTQyMzEtYTM0Yi04NTdmZDRhMDE0MGQALgAAA+xnYBMGPANEmpY/yEHuM6wBAEYSp+OGVQhHl3U8WgJ/ZQAAAw0rAAAA', 'AQAAABYAAABGEqfjhlUIR5d1PFoCf2UAAAAcRKxr')] in order_by()
when trying to print. I also want it to give me an alert if the email count is 0.
from exchangelib import Credentials, Account, UTC_NOW
from collections import defaultdict
from datetime import timedelta
credentials = Credentials('fmi#.dk', 'something')
a = Account('fmi#.dk', credentials=credentials, autodiscover=True)
counts = defaultdict(int)
testfolder = a.inbox.parent / 'Test'
since = UTC_NOW() - timedelta(hours=24)
for item in testfolder.all()\
.only('sender', 'subject')\
.filter(datetime_received__gt=since)\
.order_by('-datetime_received'):
if item.sender.email_address == 'info#something.dk':
counts[item.sender.email_address, item.subject] += 1
print(counts)

Related

How can I query the bittensor network using btcli?

btcli query
Enter wallet name (default): my-wallet-name
Enter hotkey name (default): my-hotkey
Enter uids to query (All): 18
Note that my-wallet-name, my-hotkey where actually correct names. My wallet with one of my hotkeys. And I decided to query the UID 18.
But btcli is returning an error with no specific message
AttributeError: 'Dendrite' object has no attribute 'forward_text'
Exception ignored in: <function Dendrite.__del__ at 0x7f5655e3adc0>
Traceback (most recent call last):
File "/home/eduardo/repos/bittensor/venv/lib/python3.8/site-packages/bittensor/_dendrite/dendrite_impl.py", line 107, in __del__
bittensor.logging.success('Dendrite Deleted', sufix = '')
File "/home/eduardo/repos/bittensor/venv/lib/python3.8/site-packages/bittensor/_logging/__init__.py", line 341, in success
cls()
File "/home/eduardo/repos/bittensor/venv/lib/python3.8/site-packages/bittensor/_logging/__init__.py", line 73, in __new__
config = logging.config()
File "/home/eduardo/repos/bittensor/venv/lib/python3.8/site-packages/bittensor/_logging/__init__.py", line 127, in config
parser = argparse.ArgumentParser()
File "/usr/lib/python3.8/argparse.py", line 1672, in __init__
prog = _os.path.basename(_sys.argv[0])
TypeError: 'NoneType' object is not subscriptable
What does this means?
How can I query an UID correctly?
I have try to look for UIDs to query but the tool does not give me any.
I was expecting a semantic error or a way to look for a UID i can query but not a TypeError.
It appears that command is broken and should be removed.
I opened an issue for you here: https://github.com/opentensor/bittensor/issues/1085
You can use the python API like:
import bittensor
UID: int = 18
subtensor = bittensor.subtensor( network="nakamoto" )
forward_text = "testing out querying the network"
wallet = bittensor.wallet( name = "my-wallet-name", hotkey = "my-hotkey" )
dend = bittensor.dendrite( wallet = wallet )
neuron = subtensor.neuron_for_uid( UID )
endpoint = bittensor.endpoint.from_neuron( neuron )
response_codes, times, query_responses = dend.generate(endpoint, forward_text, num_to_generate=64)
response_code_text = response_codes[0]
query_response = query_responses[0]

Retrieve Emails From Certain Date

I am trying to retrieve emails > than 12/1/2020 but get a ValueError. I tried adding .replace(microseconds=0) to str(message.ReceivedTime) but still getting this error.
error
Traceback (most recent call last):
File "C:/Users/SLID/PycharmProjects/PPC_COASplitter/PPC_Ack.py", line 178, in <module>
get_url = readEmail()
File "C:/Users/zSLID/PycharmProjects/PPC_COASplitter/PPC_Ack.py", line 144, in readEmail
if str(message.ReceivedTime) >= '2020-12-1 00:00:00' and 'P1 Cust ID 111111 File ID' in message.Subject:
File "C:\Program Files (x86)\Python37-32\lib\site-packages\win32com\client\dynamic.py", line 516, in __getattr__
ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1)
ValueError: microsecond must be in 0..999999
code
def readEmail():
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders.Item('SharedMailbox, PPC-Investigation')
inbox = folder.Folders.Item('Inbox')
messages = inbox.Items
messages.Sort("[ReceivedTime]", True)
for message in messages:
if str(message.ReceivedTime) >= '2020-12-1 00:00:00' and 'P1 Cust ID 111111 File ID' in message.Subject:
print("")
print('Received from: ',message.Sender)
print("To: ", message.To)
print("Subject: ", message.Subject)
print("Received: ", message.ReceivedTime)
print("Message: ", message.Body)
get_url = re.findall(r'(https?://[^\s]+)', message.Body)[2].strip('>')
return get_url
Firstly, you are comparing DateTime value with a string. Convert the string to a date-time value.
Secondly, never loop through all items in a folder, use Items.Restrict instead (returns a restricted Items collection):
messages = messages.Restrict("[Received] >= '1/12/2020 0:00am' ")

Value Error: Microsecond must be in 0..999999

Hi i am using the library win32com.client to read emails from an outlook sharedmailbox and i get a value error:Microsecond must be in 0..999999. I tried formatting the "ReceivedDate" as "%Y-%D-%M %H:%M:%S" with no luck. do you know what else i can try?
Question 2: im trying to count how many emails have not been replied to but i dont see a property for that in the documentation. SO i went with reading all that have a "FlagRequest" marked as completed. I would have the representatives go with this process as a way to tell if the emails have been complete.
import win32com.client
def readEmail():
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders.Item('SharedMailbox, TEST')
inbox = folder.Folders.Item('Inbox')
messages = inbox.Items
counter = 0
for message in messages:
rcvd_dt = message.ReceivedTime
if message.FlagRequest != 'Follow up' and str(rcvd_dt) >= '2020-06-01 00:00:00':
counter +=1
print(counter)
print(received_dt)
traceback:
Traceback (most recent call last):
File "C:/Users/TEST/PycharmProjects/TEST/Metrics.py", line 422, in <module>
main()
File "C:/Users/TEST/PycharmProjects/TEST/Metrics.py", line 409, in main
readEmail()
File "C:/Users/TEST/PycharmProjects/TEST/Metrics.py", line 89, in readEmail
rcvd_dt = message.ReceivedTime
File "C:\Program Files (x86)\Python37-32\lib\site-
packages\win32com\client\dynamic.py", line 516, in __getattr__
ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1)
ValueError: microsecond must be in 0..999999
What i tried:
rcvd_dt= datetime.strptime(str(rcvd_dt.split('.')[0], '%Y-%m-%d %H:%M:%S')
but get error:
valueerror: time data '2' does not match format %Y-%m-%d %H:%M:%S.%f'
if i try:
rcvd_dt= datetime.strptime(str(rcvd_dt.split('.')[0], '%Y-%m-%d %H:%M:%S.%f')
i get :
valueerror: time data '2020-06-16 08:53:56' does not match format %Y-%m-%d.%f'

Cloud firestore exceptions not caught by except block

import datetime
from threading import Timer
import firebase_admin
from firebase_admin import firestore
import calendar
db = firestore.Client()
col_ref = db.collection(u'tblAssgin').get()
current_serving = [doc.id for doc in col_ref]
#print(current_serving)
def sit_time():
for i in current_serving:
try:
doc_ref = db.collection(u'tblAssgin').document(i)
except:
current_serving.remove(doc_ref)
else:
doc = doc_ref.get()
a = doc.get('assginTime')
assign_time = datetime.datetime.fromtimestamp(calendar.timegm(a.timetuple()))
now = datetime.datetime.now()
sitting_time = now - assign_time
hours,remainder = divmod(sitting_time.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
print('minutes:',minutes)
updates = {u'sitting_time':minutes}
doc_ref.update(updates)
t = None
def refresh():
global t
sit_time()
t = Timer(60, refresh)
t.daemon = True
t.start()
refresh()
So basically the above code does that it first fetches all the document id's of collection name 'tblAssgin' and store it in 'current_serving' list. Then, loops over each document and calculate time and runs again after every 60 sec. Now suppose I delete one document then that document will not be found. So I want to do that when the document is not found exception is raised and that document id gets's removed from 'current_serving' list. But the exception is not caught.
Please help
Thanks in advance..!!
You're assuming CollectionReference.document() will throw an exception if the document does not exist. It doesn't.
>>> client.collection('non-existing').document('also-non-existing')
<google.cloud.firestore_v1beta1.document.DocumentReference object at 0x10feac208>
But DocumentReference.get() will throw an exception if the document doesn't exist.
>>> client.collection('non-existing').document('also-non-existing').get()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "~/gae/lib/python3.6/site-packages/google/cloud/firestore_v1beta1/document.py", line 432, in get
raise exceptions.NotFound(self._document_path)
google.api_core.exceptions.NotFound: 404 ~/databases/(default)/documents/non-existing/also-non-existing

AWS Boto: scan() unknown keyword 'limit'

Anyone come across this before?
import boto
conn = boto.dynamodb.connect_to_region('eu-west-1', aws_access_key_id=aws_key, aws_secret_access_key=aws_secret)
table = conn.get_table('TweetSample')
print table.scan(limit=1)
error:
Traceback (most recent call last):
File "test.py", line 9, in <module>
print table.scan(limit=1)
File "table.py", line 518, in scan
return self.layer2.scan(self, *args, **kw)
TypeError: scan() got an unexpected keyword argument 'limit'
[Finished in 0.4s with exit code 1]
I don't even know...
According to the documentation, scan method of boto.dynamodb.table.Table (which is returned by boto.dynamodb.layer2.Layer2.get_table) does not accepts limit, but max_results.
And the result is a generator. So, if you want to print it you should iterate it:
import boto.dynamodb
conn = boto.dynamodb.connect_to_region(
'eu-west-1',
aws_access_key_id=aws_key,
aws_secret_access_key=aws_secret)
table = conn.get_table('TweetSample')
for row in table.scan(max_results=1):
print row
or convert it to a sequence:
print list(table.scan(max_results=1))

Categories

Resources