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' ")
Related
I have a python script which allows me to check if a number is used on telegram or not.
I try to change the variable "phone_number" to a .txt list which basically contain phone number (There is one phone number per line)
I want the script to take a phone number from the file.txt check if it exists or not then move on to the next one and so on until all the numbers are checked.
This is what i try so far...
import random
from telethon import TelegramClient
from telethon import functions, types
import ast
api_id = XXXXX
api_hash = 'XXXXXXXXXXXXXXXXXX'
client = TelegramClient('session', api_id, api_hash)
async def main():
phone_in = []
with open('file.txt', 'r') as f:
phone_str = f.readline()
phone_in.append(ast.literal_eval(phone_str))
result = await client(functions.contacts.ImportContactsRequest(
contacts=[types.InputPhoneContact(
client_id=random.randrange(-2**63, 2**63),
phone=phone_in,
first_name='Some Name',
last_name=''
)]
))
if len(result.users):
print(f"{phone_in} has a telegram account")
await client(functions.contacts.DeleteContactsRequest(result.users))
else:
print(f"couldn't find an account for {phone_in}")
client.start()
client.loop.run_until_complete(main())
I tried this but I had an error which is the following :
Traceback (most recent call last):
File "/Users/me/phone.py", line 33, in <module>
client.loop.run_until_complete(main())
File "/usr/local/Cellar/python#3.9/3.9.1_7/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
return future.result()
File "/Users/me/phone.py", line 17, in main
result = await client(functions.contacts.ImportContactsRequest(
File "/usr/local/lib/python3.9/site-packages/telethon/client/users.py", line 30, in __call__
return await self._call(self._sender, request, ordered=ordered)
File "/usr/local/lib/python3.9/site-packages/telethon/client/users.py", line 58, in _call
future = sender.send(request, ordered=ordered)
File "/usr/local/lib/python3.9/site-packages/telethon/network/mtprotosender.py", line 174, in send
state = RequestState(request)
File "/usr/local/lib/python3.9/site-packages/telethon/network/requeststate.py", line 17, in __init__
self.data = bytes(request)
File "/usr/local/lib/python3.9/site-packages/telethon/tl/tlobject.py", line 194, in __bytes__
return self._bytes()
File "/usr/local/lib/python3.9/site-packages/telethon/tl/functions/contacts.py", line 498, in _bytes
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.contacts)),b''.join(x._bytes() for x in self.contacts),
File "/usr/local/lib/python3.9/site-packages/telethon/tl/functions/contacts.py", line 498, in <genexpr>
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.contacts)),b''.join(x._bytes() for x in self.contacts),
File "/usr/local/lib/python3.9/site-packages/telethon/tl/types/__init__.py", line 9789, in _bytes
self.serialize_bytes(self.phone),
File "/usr/local/lib/python3.9/site-packages/telethon/tl/tlobject.py", line 112, in serialize_bytes
raise TypeError(
TypeError: bytes or str expected, not <class 'list'>
Here is the same code but the phone number to check is "hardcoded"
import random
from telethon import TelegramClient
from telethon import functions, types
api_id = XXXXXXX
api_hash = 'XXXXXXXXXXXXXXXXX'
client = TelegramClient('session', api_id, api_hash)
async def main():
phone_number = '+XXXXXXXXX'
result = await client(functions.contacts.ImportContactsRequest(
contacts=[types.InputPhoneContact(
client_id=random.randrange(-2**63, 2**63),
phone=phone_number,
first_name='Some Name',
last_name=''
)]
))
if len(result.users):
print(f"{phone_number} has a telegram account")
await client(functions.contacts.DeleteContactsRequest(result.users))
else:
print(f"couldn't find an account for {phone_number}")
client.start()
client.loop.run_until_complete(main())
Does anyone know how I can assign the file.txt to the phone_in variable?
If ImportContactsRequests expects one phone number at a time, then you have to call it for each phone number. That will create multiple records for a single name, but if the API doesn't allow multiple phone numbers per person, you'll have to decide how to handle it.
with open('file.txt', 'r') as f:
phone_str = f.readline()
result = await client(functions.contacts.ImportContactsRequest(
contacts=[types.InputPhoneContact(
client_id=random.randrange(-2**63, 2**63),
phone=phone_str,
first_name='Some Name',
last_name=''
)]
))
if len(result.users):
print(f"{phone_number} has a telegram account")
await client(functions.contacts.DeleteContactsRequest(result.users))
else:
print(f"couldn't find an account for {phone_number}")
According to the doc of InputPhoneContact, the phone argument takes string type not list. So you could read all phones in the file.txt first, then loop through the list.
async def main():
phone_in = []
with open('file.txt', 'r') as f:
phone_str = f.readline()
phone_in.append(ast.literal_eval(phone_str))
for phone in phone_in:
result = await client(functions.contacts.ImportContactsRequest(
contacts=[types.InputPhoneContact(
client_id=random.randrange(-2**63, 2**63),
phone=phone,
first_name='Some Name',
last_name=''
)]
))
if len(result.users):
print(f"{phone} has a telegram account")
await client(functions.contacts.DeleteContactsRequest(result.users))
else:
print(f"couldn't find an account for {phone}")
python does allow for creation of heterogeneous lists, so not sure why this is throwing an error. Depending on the version in use, maybe there is a constraint on the type homogeneity in the list.I'm not sure though...but curious to know if the following works?
Can you try with a small version of the file in which the numbers are of the same 'type'?
Alternately, can try with a x.strip("[/{(") before appending it to phone_in.
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)
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'
I am trying to get the email addresses of AD group members of a particular LDAP group using python.
I have following code. The Print m statement writes something like below.
Output:
CN=Admin_abc20,OU=Admin ID's,OU=TEST1,DC=other_example,DC=example,DC=com
CN=leterd,OU=Employees,OU=BACD,DC=na,DC=example,DC=com
CN=mytest37,OU=Employees,OU=SUNPH,DC=na,DC=example,DC=com
CN=Doe Mestre\, John,OU=Partners & Contractors,OU=TEST1,DC=other_example,DC=example,DC=com
CN=Robin\, Mark [ABCD],OU=Partners & Contractors,OU=JJCUS,DC=na,DC=example,DC=com
CN=San Irdondo\, Paul [TEST1 Non-ABC],OU=Partners & Contractors,OU=TEST1,DC=other_example,DC=example,DC=com
My Code:
def get_group_members(group_name, ad_conn, basedn=AD_USER_BASEDN):
members = []
ad_filter = AD_GROUP_FILTER.replace('My_Group_Name', group_name)
result = ad_conn.search_s(basedn, ldap.SCOPE_SUBTREE, ad_filter)
if result:
if len(result[0]) >= 2 and 'member' in result[0][1]:
members_tmp = result[0][1]['member']
for m in members_tmp:
print m
#email = ad_conn.search_s(m, ldap.SCOPE_SUBTREE,'(objectClass=*)',['mail'])
#print email
Now when I remove comment from last 2 lines of my code to get the email address of persons, I get following error, please note that I have changed by company's ldap identifiers to example/test.
Can you please help me with this? I am a newbie to python.
Traceback (most recent call last):
File "/app/abc/python/Test_new.py", line 81, in <module>
group_members = get_group_members(group_name, ad_conn)
File "/app/abc/python/Test_new.py", line 58, in get_group_members
email = ad_conn.search_s(m, ldap.SCOPE_SUBTREE,'(objectClass=*)', ['mail'])
File "/usr/lib64/python2.6/site-packages/ldap/ldapobject.py", line 516, in search_s
return self.search_ext_s(base,scope,filterstr,attrlist,attrsonly,None,None,timeout=self.timeout)
File "/usr/lib64/python2.6/site-packages/ldap/ldapobject.py", line 510, in search_ext_s
return self.result(msgid,all=1,timeout=timeout)[1]
File "/usr/lib64/python2.6/site-packages/ldap/ldapobject.py", line 436, in result
res_type,res_data,res_msgid = self.result2(msgid,all,timeout)
File "/usr/lib64/python2.6/site-packages/ldap/ldapobject.py", line 440, in result2
res_type, res_data, res_msgid, srv_ctrls = self.result3(msgid,all,timeout)
File "/usr/lib64/python2.6/site-packages/ldap/ldapobject.py", line 446, in result3
ldap_result = self._ldap_call(self._l.result3,msgid,all,timeout)
File "/usr/lib64/python2.6/site-packages/ldap/ldapobject.py", line 96, in _ldap_call
result = func(*args,**kwargs)
ldap.REFERRAL: {'info': 'Referral:\nldap://ab.example.com/CN=Radfde3,OU=Partners%20&%20Contractors,OU=JANBE,DC=eu,DC=example,DC=com', 'desc': 'Referral'}
I don't know much about Python but I think your problem is with the LDAP filter. Try this for the last 2 lines of code:
email = ad_conn.search_s(m, ldap.SCOPE_SUBTREE,'(&(objectClass=person)(mail=*))')
print email
I hope this helps!
getting this error when running our newly implemented Reporting API v4
It runs successfully for most of our clients, but runs into this error for a select few. Would love some help figuring it out as I'm a little stuck.
Traceback (most recent call last):
File "v4analytics.py", line 424, in <module>
main()
File "v4analytics.py", line 420, in main
extract_all(service)
File "v4analytics.py", line 146, in extract_all
for profile_results in run_queries_per_day(service, profile_id, profile_name):
File "v4analytics.py", line 205, in run_queries_per_day
print 'rowCount: %s' % results['reports'][0]['data']['rowCount']
KeyError: 'rowCount'
Error is coming from this section of code:
def run_queries_per_day(service, profile_id, profile_name):
""" Runs the query for one profile and return the data """
start_date = parse_date(settings.START_DATE)
end_date = parse_date(settings.END_DATE)
date_range = end_date - start_date
for day_delta in range(0, date_range.days + 1):
current_day = start_date + timedelta(day_delta)
print 'Day: %s' % current_day
has_next = True
next_page_token = '0'
while has_next:
# temp fix for 429 RESOURCE_EXHAUSTED AnalyticsDefaultGroupUSER-100s:
time.sleep(settings.WAIT_BETWEEN_REQUESTS_SECONDS)
query = build_query(service,
profile_id,
format_date(current_day),
format_date(current_day),
next_page_token=next_page_token,
)
results = query.execute()
next_page_token = results['reports'][0].get('nextPageToken')
if not next_page_token:
has_next = False
print 'rowCount: %s' % results['reports'][0]['data']['rowCount']
if contains_sampled_data(results):
with open(settings.SAMPLEDDATA_FILE, 'a') as sample_file:
sample_file.write('profile_id: %s\n' % profile_id)
sample_file.write('profile_name: %s\n' % profile_name)
sample_file.write('\n')
yield build_response(results, profile_id, profile_name)
print
Thanks for any help