ananas The Python Bot Framework for Mastodon开源项目

我要开发同款
匿名用户2021年11月08日
36阅读
开发技术Python
所属分类应用工具、IM/聊天/语音工具
授权协议MIT License

作品详情

AnanasWhatisAnanas?

Ananasallowsyoutowritesimple(orcomplicated!)mastodonbotswithouthavingtorewriteconfigfileloading,interval-basedposting,scheduledposting,auto-replying,andsoon.

Somebotsareassimpleasaconfigurationfile:

[bepis]class=tracery.TraceryBotaccess_token=....grammar_file="bepis.json"

Butit'seasytowriteonewithcustomizedbehavior:

classMyBot(ananas.PineappleBot):defstart(self):withopen('trivia.txt','r')astrivia_file:self.trivia=trivia_file.lines()@hourly(minute=17)defpost_trivia(self):self.mastodon.toot(random.choice(self.trivia))@replydefrespond_trivia(self,status,user):self.mastodon.toot("@{}:{}".format(user["acct"],random.choice(self.trivia)))

Runmultiplebotsonmultipleinstancesoutofasingleconfigfile:

[jorts]class=custom.JortsBotdomain=botsin.spaceaccess_token=....line=632[roll]class=roll.DiceBotdomain=cybre.spaceaccess_token=....

AndusetheDEFAULTsectiontosharecommonconfigurationoptionsbetweenthem:

[DEFAULT]domain=cybre.spaceclient_id=....client_secret=....Gettingstartedpipinstallananas

Theananaspippackagecomeswithascripttohelpyoumanageyourbots.

Simplygiveitaconfigfileandit'llloadyourbotsandclosethemsafelywhenitreceivesakeyboardinterrupt,SIGINT,SIGTERM,orSIGKILL.

ananasconfig.cfg

Ifyouhaven'tspecifiedaclientid/secretoraccesstoken,thescriptwillexitunlessyourunitwiththe--interactiveflag,whichallowsittopromptyoufortheinstancelogininformation.(Theonlypartoftheinputyouenterherethat'sstoredintheconfigfileistheinstancename--theemailandpasswordareonlyusedtogeneratetheaccesstoken).

Configuration

ThefollowingfieldsareinterpretedbythePineappleBotbaseclasssandwillworkforeverybot:

class:thefully-specifiedpythonclassthattherunnerscriptshouldinstantiatetostartyourbot.e.g."ananas.default.TraceryBot"

domain¹:thedomainoftheinstancetoruntheboton.Mustsupporthttpsconnections.Onlyincludethedomain,noprotocolorslashes.e.g."mastodon.social"

client_id¹,client_secret¹:thetokensthattheinstanceusestoidentifywhatclientthisbotispostingfrom/as.Willbeusedtodeterminewhat'sdisplayedunderneathallthepostsmadebythisbot.

access_token¹:theaccesstokenusedtoauthenticateAPIrequestswiththeinstance.Makesurethisissecret,don'tdistributeconfigfileswiththisfieldfilledoutorpeoplewillbeabletopostundertheaccountthistokenwascreatedwith.

admin:thefullusername(withoutleading@)oftheusertoDMerrorreportsto.Canbeleftunspecified,butisusefulforkeepinganeyeonthehealthofthebotwithoutconstantlymonitoringthescriptlogs.e.g.admin@example.town

¹:Filledoutautomaticallyifthebotisrunininteractivemode.

Additionalfieldsarespecifictothetypeofbot,refertothedocumentationforthebot'sclassformoreinformationaboutthefieldsitexpects.

WritingBots

Custombotclassesshouldbesubclassesofananas.PineappleBot.Ifyouoverride__init__,besuretocallthebaseclass's__init__.

Decorators

Inorderforthebottodoanything,youshouldaddamethoddecoratedwithatleastoneofthefollowingdecorators:

@ananas.reply:Callsthedecoratedfunctionwhenthebotismentionedbyanyotheruser.Decoratortakesnoparameters,butshouldonlybecalledonfunctionsmatchingthissignature:defreply_fn(self,mention,user).mentionwillbethedictionarycorrespondingtothestatuscontainingthemention(asreturnedbythemastodonAPI,userwillbethedictionarycorrespondingtotheuserthatmentionedthebot.

@ananas.interval(secs):Callsthedecoratedfunctioneverysecsseconds,startingwhenthebotisinitialized.Forintervalslongerthan~anhour,youmaywanttouse@scheduleinstead.e.g.@ananas.interval(60)

@ananas.schedule(**kwargs):Allowsyoutoschedule,cron-style,thedecoratedfunction.Acceptedkeywordsare"second","minute","hour","day_of_week"or"day_of_month"(butnotboth),"month",and"year".Ifanyofthesekeywordsarenotspecified,theywillbetreatedlikecrontreatsan*,thatis,aslongasthetimematchestheothervalues,anyvaluewillbeaccepted.Speakingofwhich,thecron-likesyntax"*"aswellas"*/3"arebothaccepted,andwillexpandtotheexpectedthing:forexample,schedule(hour="*/2",minute="*/10")willpostevery10minutesduringhourswhicharemultiplesof2.

@ananas.hourly(minute=0),@ananas.daily(hour=0,minute=0):Shortcutsfor@ananas.schedule()thatcallthedecoratedfunctiononceanhouratthespecifiedminuteoronceadayatthespecifiedhourandminute.Ifparametersareomittedthey'llpostatthetopofthehourormidnight(UTC).

@ananas.error_reporter:specifiescustombehaviorforreportingerrors.Thedecoratedfunctionshouldmatchthissignature:deferr(self,error)whereerrorisastringrepresentationoftheerror.

OverrideableFunctions

Youcanalsodefinethefollowingfunctionsandtheywillbecalledattherelevantpointsinthebot'slifecycle:

init(self):calledbeforetheconfigurationfilehasbeenloaded,sothatyoucansetdefaultvaluesforconfigfieldsincasetheconfigfiledoesn'tspecifythem.

start(self):calledafteralloftheinternalPineappleBotinitializationiscompleteandthemastodonAPIisreadytouse.Agoodplacetoloadfilesspecifiedintheconfig,postastartupnotice,orotherwisedobot-specificsetup.

stop(self):calledwhenthebothasreceivedashutdownsignalandneedstostop.Theconfigfilewillbesavedafterthis,soifyouneedtomakeanylastminutechangestotheconfig,dothathere.

ConfigurationFields

Alloftheconfigurationfieldsforthecurrentbotareavailablethroughtheself.configobject,whichexposesthemwithbothfield-accessorsyntaxanddictionary-accessorsyntax,forexample:

foo=self.config.foobar=self.config["bar"]

Thesecanberead(togettheuser'sconfigurationdata)orwrittento(toaffecttheconfigfileonnextsave)ordeleted(toremovethatfieldfromtheconfigfile).

Youcancallself.config.load()togetthelatestvaluesfromtheconfigfile.loadtakesanoptionalparametername,whichisthenameofthesectiontoloadintheconfigfileincaseyouwanttoloadadifferentonethanthebotwasstartedwith.

Youcanalsocallself.config.save()towriteanychangesmadesincethelastloadbacktotheconfigfile.

Notethatifyoucallself.config.load()duringbotoperation,withoutfirstcallingself.config.save(),youwilldiscardanychangesmadetotheconfigurationsincethelastload.

DistributingBots

Youcandistributebotshoweveryouwant;aslongastheclassisavailableinsomemoduleinpython'ssys.pathoramoduleaccessiblefromthecurrentdirectory,therunnerscriptwillbeabletoloadit.

Ifyouthinkyourbotmightbegenerallyusefultootherpeople,feelfreetocreateapullrequestonthisrepositorytogetitaddedtothecollectionofdefaultbots.

Questions?PingmeonMastodonat@chr@cybre.spaceorshootmeanemailatchr@cybre.spaceandI'llanswerasbestIcan!

声明:本文仅代表作者观点,不代表本站立场。如果侵犯到您的合法权益,请联系我们删除侵权资源!如果遇到资源链接失效,请您通过评论或工单的方式通知管理员。未经允许,不得转载,本站所有资源文章禁止商业使用运营!
下载安装【程序员客栈】APP
实时对接需求、及时收发消息、丰富的开放项目需求、随时随地查看项目状态

评论