0

So, I made some code that takes events from a google calendar and organizes them then posts them on discord. The main problem is this: client.send_message(client.get_channel('483988804370169857'),"None") When using this code in a @client.event it works fine, the problem begins when i put it in a normal function. I need it in a normal function so that it runs once every 24 hours. No errors, no nothing. The code just goes through the function and doesn't send the message. How can I fix this?

from __future__ import print_function
import json
import datetime
import discord
from discord.ext import commands
from datetime import timedelta
import gspread
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
from discord.ext import commands
import threading



SCOPES = 'https://www.googleapis.com/auth/calendar.readonly'


client = discord.Client()



def Hw():
    print("HW")
    now = datetime.datetime.now()
    run_at = now + timedelta(hours=3)
    delay = (run_at - now).total_seconds()
    #Begin Google Calander API
    store = file.Storage('token.json')
    creds = store.get()
    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
        creds = tools.run_flow(flow, store)
    service = build('calendar', 'v3', http=creds.authorize(Http()))
    now = datetime.datetime.utcnow().isoformat() + 'Z' 
        #Retrieve all Events
    events_result = service.events().list(calendarId='CENSORED', timeMin=now,maxResults=250, singleEvents=True,orderBy='startTime').execute()
    events = events_result.get('items', [])

        #Currentmode stores if searching for tommorow, the week, or other (1,2,3)
    Currentmode = 0
    UMode=1
    none = True
        #Gets end of week
    dt = datetime.datetime.now()
    startweek = dt - timedelta(days=dt.weekday())
    endweek = startweek + timedelta(days=6)
    dtstring = str(dt.date())
    TheMessages = "**" + dtstring + " Report**"
    client.send_message(client.get_channel('483988804370169857'),TheMessages)
    if not events:
        client.send_message(client.get_channel('483988804370169857'), 'No upcoming events found.')
    for event in events:

        if Currentmode == 0:
            client.send_message(client.get_channel('483988804370169857'),"*Due Tommorow*")
            Currentmode = 1  

        thestr = event['start'].get('dateTime')

        count = 0
        count2 = 0
        for x in thestr:
            count += 1
            if x == "-":
                count2 +=1
                if count2 == 3:
                    break
        count = count - 1
        thestr = thestr[0:count]


        start = datetime.datetime.strptime(thestr, "%Y-%m-%dT%H:%M:%S")

        if (start - dt).days <= 7 and Currentmode == 1:
            if UMode == 1:
                client.send_message(client.get_channel('483988804370169857'),"None")
            client.send_message(client.get_channel('483988804370169857'),"*Due in the Next 7 Days*")
            UMode = 2
            Currentmode = 2
        elif (start - dt).days >= 7 and (Currentmode == 1 or Currentmode == 2):
            if UMode == 1:
                client.send_message(client.get_channel('483988804370169857'),"None")
                client.send_message(client.get_channel('483988804370169857'),"*Due in the Next 7 Days*")
                client.send_message(client.get_channel('483988804370169857'),"None")
            client.send_message(client.get_channel('483988804370169857'),"*Longterm*") 
            Currentmode = 3
            UMode = 3
        FirstMessage = str(start.date())
        SecondMessage = event['summary']
        ThirdMessage= FirstMessage + " " + SecondMessage
        client.send_message(client.get_channel('483988804370169857'),ThirdMessage)
@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('!hello'):
        msg = 'Hello {0.author.mention}'.format(message)
        await client.send_message(message.channel, msg)
@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')
    now = datetime.datetime.now()
    run_at = now + timedelta(seconds=1)
    delay = (run_at - now).total_seconds()
    threading.Timer(delay, Hw).start()



#Run client and start daily timer       
client.run('CENSORED')
  • 1
    `client.send_message` is a coroutine and must be awaited using `await`, as you have done in your `on_message` event. – Benjin Sep 02 '18 at 18:21
  • when using await, for some reason it shows up a syntax error @Benjin –  Sep 02 '18 at 19:06
  • You can't `await` outside a coroutine (an `async def` function). I'm not sure there's a good way of incorporating asynchronous code with `threading` in python. For repeating tasks see: [How can I periodically execute a function with asyncio?](https://stackoverflow.com/questions/37512182/how-can-i-periodically-execute-a-function-with-asyncio). You should also read the [asyncio documentation](https://docs.python.org/3.5/library/asyncio-task.html#tasks-and-coroutines) – Patrick Haugh Sep 02 '18 at 20:40
  • @PatrickHaugh Thanks! I looked through the documentation and fixed my loop! –  Sep 02 '18 at 21:36

0 Answers0